登录
首页 >  Golang >  Go问答

存储 JSON 字符串到数据库的最佳方法是什么?

来源:stackoverflow

时间:2024-02-16 14:39:25 133浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《存储 JSON 字符串到数据库的最佳方法是什么?》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我从服务器获取 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 ?我希望这个问题有意义。

谢谢


正确答案


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)

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>