我從服務器獲得 JSON 回應,并希望將其保存到資料庫中,其中一列是 JSON 列。回應類似于以下內容:
msgJson = [{"id": 1, "type": "dog", "attributes": {"weight":20, "sound":"bark"}}]
所以我目前正在制作一個結構并嘗試更新資料庫中的每個元素。
type Animal struct {
Id int `json:"id"`
Type string `json:"type"`
Attributes string `json:"attributes"`
}
var animals []Animal
json.Unmarshal([]byte(msgJson), &animals)
sqlStatement := `
UPDATE animals
SET type = $2, attributes = $3
WHERE id = $1;`
_, err := db.Exec(
sqlStatement,
animals[0].Id,
animals[0].Type,
animals[0].Attributes)
當然,這是行不通的,因為該attributes欄位應該是 JSON。
我相信我可以將 JSON 解組為嵌套結構,然后在更新資料庫時對其進行編組,但由于這將有很多欄位,有沒有辦法在添加到資料庫時獲取字串并立即將其表示為 JSON?我希望這個問題是有道理的。
謝謝
uj5u.com熱心網友回復:
將attributes欄位解組為json.RawMessage。將原始訊息保存到資料庫。
type Animal struct {
Id int `json:"id"`
Type string `json:"type"`
Attributes json.RawMessage `json:"attributes"`
}
?
_, err := db.Exec(
sqlStatement,
animals[0].Id,
animals[0].Type,
animals[0].Attributes)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/436602.html
標籤:走
