gpt4 book ai didi

json - 解码具有不同结构但相同键的嵌套 JSON

转载 作者:行者123 更新时间:2023-12-01 22:33:50 24 4
gpt4 key购买 nike

我正在尝试解码一些嵌套的 JSON,如下所示:

{
"id": "aRandomId",
"type": "aRandomType",
"aRandomField": {
"type": "someType",
"createdAt": "2020-07-07T15:50:02",
"object": "anObject",
"modifiedAt": "2020-07-07T15:50:02"
},
"aParameter": {
"type": "Property",
"createdAt": "2020-07-07T15:50:02",
"value": "myValue",
"modifiedAt": "2020-07-07T15:50:02"
},
"location": {
"type": "GeoProperty",
"value": {
"type": "Point",
"coordinates": [
7.0054,
40.9999
]
}
},
... other things with type, value ...

"createdAt": "2020-07-07T15:50:02",
"modifiedAt": "2020-07-07T15:50:02",
}

我想获取所有键和值:类型、createdAt、值(如果它们是嵌套的)
实际上,我有 2 个结构:
type Attribute struct {
Type string `json:"type"`
CreatedAt string `json:"createdAt"`
Value string `json:"value"`
ModifiedAt string `json:"modifiedAt"`
}

type Entity struct {
Id string `json:"id"`
Type string `json:"type"`
CreatedAt string `json:"createdAt"`
Attribute Attribute
}


in := []byte(buf.String())
var entity Entity
err := json.Unmarshal(in, &entity)
if err != nil {
panic(err)
}

frame.Fields = append(frame.Fields,
data.NewField("key", nil, []string{"type : ", "createdAt : ", "name : "}),
)
frame.Fields = append(frame.Fields,
data.NewField("value", nil, []string{entity.Type, entity.CreatedAt, entity.Attribute.Value}),
)
问题是可能有几个不同的属性结构,我不能全部提供它们。
我想在一帧中显示所有键(仅类型、createdAt 和值),并在另一帧中显示它们的所有值。
也许有类似的东西?
type Entity struct {
attribute List<Attribute>
}
type Attribute struct{
Type string
CreatedAt string
Value string
ModifiedAt string
}

最佳答案

The problem is there can be several different Attribute struct andIi can't provide them all


看起来您的 JSON 数据可以具有一组具有相似值 ( Attribute) 的键,并且您无法知道数据中可能有多少键。
对于这种情况,您可以使用 map[string]json.RawMessage作为解码的起始实体
var e map[string]json.RawMessage
if err := json.Unmarshal([]byte(jsonData), &e); err != nil {
panic(err)
}
然后,您可以对这些值进行范围检查,看看是否可以将它们解码为 Attribute。类型
for k, v := range e {
var a Attribute
if err := json.Unmarshal(v, &a); err == nil {
log.Printf("Got attribute %s: %s", k, string(v))
}
}
Run it on playground

关于json - 解码具有不同结构但相同键的嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62789193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com