将 JSON 反序列化为 PostgreSQL 数据库中的 JSON 字段

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

Unmarshall json into database json field for postgres

问题

给定这个 JSON - { "Id": 1, "ContactInfo": {"email1": "xx@yy.com", "phone1": "2223334444"}},我们如何将 JSON 解组成结构体 A。ContactInfo 只是一个简单的 JSON 数据类型在 postgres 中。我已经找了一下,但似乎找不到任何简单的方法。如果没有任何特殊处理,我只是得到一个错误,如果我使用 json.Unmarshal(错误信息为 - json: cannot unmarshal object into Go value of type string)。

期望的是将 ContactInfo 保持为字符串,这样我们可以直接将其发送到 postgres,并且 postgres 将验证它是否为有效的 JSON。然而,Id 应该被解组并分配为结构体的值。

英文:
type A struct {
   Id int64
   ContactInfo sql.NullString `sql:"type:json"`
}

Given this json - {"Id": 1, "ContactInfo": {"email1": "xx@yy.com", "phone1": "2223334444"}}, how do we go about Unmarshaling the json into struct A. ContactInfo is just a simple json data type in postgres. I've looked around, but can't seem to find any easy way. Without any special handling, I simply get an error if I json.Unmarshal (error reads - json: cannot unmarshal object into Go value of type string).

What is desired is to leave ContactInfo untouched as a string so we can send it into postgres directly and postgres will verify if its valid json. However, Id should be unmarshaled and assigned as struct value.

答案1

得分: 7

解析包含嵌套JSON的JSON,你需要使用json.RawMessage类型的字段(以及第二个struct)。

查看这个示例以了解基本用法。然后,你将可以访问原始字段内容,以在与数据库相关的结构中使用。

英文:

To parse JSON with embedded JSON you need to use a field of type json.RawMessage (and a second struct).

Check out this example for basic usage. You will then have access to the raw field contents for use in your database related structure.

huangapple
  • 本文由 发表于 2014年5月22日 03:34:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/23792234.html
匿名

发表评论

匿名网友

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

确定