我想將某個結構存儲到我的數據庫中,其中包含一個 JSON 字段。type Comp struct { CompId int64 `db:"comp_id" json:"comp_id"` StartDate time.Time `db:"start_date" json:"start_date"` EndDate time.Time `db:"end_date" json:"end_date"` WeeklySchedule json.RawMessage `db:"weekly_schedule" json:"weekly_schedule"`}該表的架構是:CREATE TABLE IF NOT EXISTS Tr.Comp( comp_id SERIAL, start_date timestamp NOT NULL, end_date timestamp NOT NULL, weekly_schedule json NOT NULL, PRIMARY KEY (comp_id));我在我的項目中使用 sqlx 和 lib/pq 驅動程序,以下將不會執行。相反,它恐慌地說有一個 nil 指針。DB 是一個全局*sqlx.DB結構 tx := DB.MustBegin() compFixture := Comp{ StartDate: time.Now(), EndDate: time.Now().AddDate(1, 0, 0), WeeklySchedule: json.RawMessage([]byte("{}")), } _, err = tx.NamedExec( `INSERT INTO Tr.Comp(comp_id, start_date, end_date, weekly_schedule) VALUES (DEFAULT, :start_date, :end_date, :weekly_schedule) RETURNING comp_id;`, compFixture) if err != nil { t.Fatal("Error creating fixture.", err) }當我weekly_schedule從架構和夾具中刪除時,一切正常。但是由于某種原因,當包含此字段時,程序會出現混亂。關于我應該如何weekly_schedule在我的數據庫架構和 Go 結構中定義字段的任何想法?
3 回答

蕭十郎
TA貢獻1815條經驗 獲得超13個贊
從 go 文檔:
json.RawMessage is a raw encoded JSON object. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.
如果您在包 json json.RawMessage 中提供的示例中 log.Printf("%#", colors) 您可以看到在解組 json 對象 'Point'-member 后未解組而是保留 []byte 格式,直到color-format 是固定的,'Point' 被明確地解組。
在將它放入數據庫之前,您是否嘗試過解組 WeeklySchedule 之類的東西?
- 3 回答
- 0 關注
- 360 瀏覽
添加回答
舉報
0/150
提交
取消