Go - 将 JSON 字符串保存到数据库中(最有效?)

Go - Save JSON string into a DB (most efficient?)

我从服务器收到 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 = , attributes = 
    WHERE id = ;`

_, err := db.Exec(
    sqlStatement,
    animals[0].Id,
    animals[0].Type,
    animals[0].Attributes)

当然这样不行,因为attributes字段应该是JSON.

我相信我可以将 JSON 解组为嵌套结构,然后在更新数据库时将其编组,但是由于这将有很多字段,是否有一种方法可以获取字符串并立即将其表示为JSON 添加到数据库时?我希望这个问题是有道理的。

谢谢

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)