我正在嘗試將 JSON 字節存儲到后greSQL,但有一個問題。\u0000 無法轉換為文本。正如您在下面看到的,JSON包含諸如 之類的轉義序列,似乎PostgreSQL將其解釋為unicode字符,而不是JSON字符串。\u0000err := raws.SaveRawData(data, url)// if there is "\u0000" in the bytesif err.Error() == "ERROR: unsupported Unicode escape sequence (SQLSTATE 22P05)" { // try to remove \u0000, but not work data = bytes.Trim(data, "\u0000") e := raws.SaveRawData(data, url) // save data again if e != nil { return e // return the same error } return nil}保存的結構是:type RawJSONData struct { ID uint64 `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"-"` DeletedAt gorm.DeletedAt `json:"-" gorm:"index"` Data datatypes.JSON `json:"data"` URL string `gorm:"index" json:"url"`}datatypes.JSON來自 gorm.io/datatypes。它似乎只是,它是(延伸自?)一個。json.RawMessage[]byte我使用后greSQL的類型來存儲這些數據。JSONB桌子:create table raw_json_data( id bigserial not null constraint raw_json_data_pke primary key, created_at timestamp with time zone, deleted_at timestamp with time zone, data jsonb, url text);
1 回答

慕沐林林
TA貢獻2016條經驗 獲得超9個贊
統一碼轉義序列在后記和列中根本不受支持:\u0000TEXTJSONB
jsonb 類型也會拒絕 \u0000(因為這不能在 PostgreSQL 的文本類型中表示)
您可以將列類型更改為:JSON
create table Foo (test JSON);
insert into Foo (test) values ('{"text": "明天再水\u0000綠塔的"}');
-- works
json 數據類型存儲輸入文本的精確副本
這樣做的好處是可以使數據與您從 API 接收的數據相同,以防轉義序列具有需要保留的某些含義。
它還允許您使用 Postgres JSON 運算符(例如 )進行查詢,盡管將 JSON 字段轉換為文本仍將失?。?>>\u0000
select test->>'text' from Foo
-- ERROR: unsupported Unicode escape sequence
類型的列也接受任何字節序列,而無需操作數據。在戈爾姆,使用 標簽:BYTEAtype:bytea
type RawJSONData struct {
// ... other fields
Data string `gorm:"type:bytea" json:"data"`
}
如果上述任何一項對您來說都不可接受,那么您必須清理輸入字符串...
- 1 回答
- 0 關注
- 219 瀏覽
添加回答
舉報
0/150
提交
取消