我正在嘗試解組一些嵌套的 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、值(如果它們是嵌套的)實(shí)際上,我有 2 個結(jié)構(gòu):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}), )問題是可能有幾個不同的屬性結(jié)構(gòu),我不能全部提供它們。我想在一幀中顯示所有鍵(僅類型、createdAt 和值),并在另一幀中顯示它們的所有值。也許有類似的東西?type Entity struct { attribute List<Attribute>}type Attribute struct{ Type string CreatedAt string Value string ModifiedAt string }
1 回答

PIPIONE
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超9個贊
問題是可能有幾個不同的屬性結(jié)構(gòu),我不能全部提供
看起來您的 JSON 數(shù)據(jù)可以有一組具有相似值 ( Attribute) 的鍵,而您無法知道數(shù)據(jù)中可能有多少鍵。
對于這種情況,您可以使用 amap[string]json.RawMessage作為起始實(shí)體來解組
var e map[string]json.RawMessage
if err := json.Unmarshal([]byte(jsonData), &e); err != nil {
panic(err)
}
然后,您可以在值范圍內(nèi)查看是否可以將它們解組為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))
}
}
- 1 回答
- 0 關(guān)注
- 162 瀏覽
添加回答
舉報(bào)
0/150
提交
取消