如何使用 Golang 解组动态 json 对象
How to unmarshal dynamic json objects with Golang
首先让我告诉你我是围棋世界的新手。
我想做的是阅读 json 我从 JSON API 得到的(我不控制)。一切正常,我也可以显示收到的 ID 和标签。但是 fields 字段有点不同,因为它是一个动态数组。
我可以从 api 收到这个:
{
"id":"M7DHM98AD2-32E3223F",
"tags": [
{
"id":"9M23X2Z0",
"name":"History"
},
{
"id":"123123123",
"name":"Theory"
}
],
"fields": {
"title":"Title of the item",
"description":"Description of the item"
}
}
或者我只能接收 description
,而不是 title
和 description
,或者接收另一个随机对象,如 long_title
。对象 return 可能完全不同,并且可以是无限可能的对象。但它总是 returns 带有键和字符串内容的对象,就像示例中那样。
到目前为止,这是我的代码:
type Item struct {
ID string `json:"id"`
Tags []Tag `json:"tags"`
//Fields []Field `json:"fields"`
}
// Tag data from the call
type Tag struct {
ID string `json:"id"`
Name string `json:"name"`
}
// AllEntries gets all entries from the session
func AllEntries() {
resp, _ := client.Get(APIURL)
body, _ := ioutil.ReadAll(resp.Body)
item := new(Item)
_ = json.Unmarshal(body, &item)
fmt.Println(i, "->", item.ID)
}
所以 Item.Fields 是动态的,无法预测键名是什么,因此据我所知,无法为其创建结构。但同样,我是 Go 的新手,有人可以给我任何提示吗?谢谢
如果 "fields"
中的数据始终是 flat-dict,那么您可以使用 map[string]string
作为 Fields
.
的类型
对于任意数据,将 Fields
指定为 RawMessage
type and parse it later on based on its content. Example from docs: https://play.golang.org/p/IR1_O87SHv
如果字段太不可预测,那么你可以保持这个字段原样([]byte
)或者如果有一些字段总是通用的,那么你可以解析这些字段并保留其余的(但是这会导致其他字段中存在的数据丢失)。
首先让我告诉你我是围棋世界的新手。
我想做的是阅读 json 我从 JSON API 得到的(我不控制)。一切正常,我也可以显示收到的 ID 和标签。但是 fields 字段有点不同,因为它是一个动态数组。
我可以从 api 收到这个:
{
"id":"M7DHM98AD2-32E3223F",
"tags": [
{
"id":"9M23X2Z0",
"name":"History"
},
{
"id":"123123123",
"name":"Theory"
}
],
"fields": {
"title":"Title of the item",
"description":"Description of the item"
}
}
或者我只能接收 description
,而不是 title
和 description
,或者接收另一个随机对象,如 long_title
。对象 return 可能完全不同,并且可以是无限可能的对象。但它总是 returns 带有键和字符串内容的对象,就像示例中那样。
到目前为止,这是我的代码:
type Item struct {
ID string `json:"id"`
Tags []Tag `json:"tags"`
//Fields []Field `json:"fields"`
}
// Tag data from the call
type Tag struct {
ID string `json:"id"`
Name string `json:"name"`
}
// AllEntries gets all entries from the session
func AllEntries() {
resp, _ := client.Get(APIURL)
body, _ := ioutil.ReadAll(resp.Body)
item := new(Item)
_ = json.Unmarshal(body, &item)
fmt.Println(i, "->", item.ID)
}
所以 Item.Fields 是动态的,无法预测键名是什么,因此据我所知,无法为其创建结构。但同样,我是 Go 的新手,有人可以给我任何提示吗?谢谢
如果 "fields"
中的数据始终是 flat-dict,那么您可以使用 map[string]string
作为 Fields
.
对于任意数据,将 Fields
指定为 RawMessage
type and parse it later on based on its content. Example from docs: https://play.golang.org/p/IR1_O87SHv
如果字段太不可预测,那么你可以保持这个字段原样([]byte
)或者如果有一些字段总是通用的,那么你可以解析这些字段并保留其余的(但是这会导致其他字段中存在的数据丢失)。