Go – 将JSON字符串保存到数据库中(最高效的方法?)

huangapple go评论72阅读模式
英文:

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 = $2, attributes = $3
	WHERE id = $1;`

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

当然,这不起作用,因为attributes字段应该是JSON类型的。

我认为我可以将JSON解组为嵌套的结构体,然后在更新数据库时进行编组,但由于这将有很多字段,是否有一种方法可以在添加到数据库时将字符串立即表示为JSON?希望这个问题说得清楚。

谢谢。

英文:

I am getting a JSON response from a server and want to save that into a db, where one of the columns is a JSON column. The response looks similar to the following:

msgJson = [{"id": 1, "type": "dog", "attributes": {"weight":20, "sound":"bark"}}]

So I am currently making a struct and trying to update each element in the DB.

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)

Of course, this doesn't work, because the attributes field is supposed to be JSON.

I believe I could Unmarshal the JSON into nested structs, and then Marshal it when updating the DB, but since this will have many fields, is there a way to take the string and immediately represent it as JSON when adding to the DB? I hope that question makes sense.

Thank you

答案1

得分: 1

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)
英文:

Unmarshal the attributes field to a json.RawMessage. Save the raw message to the database.

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)

huangapple
  • 本文由 发表于 2022年3月2日 11:22:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/71317089.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定