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

标签 json go struct

我正在尝试解码一些嵌套的 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/

相关文章:

javascript - 使用 JSON 多标记在 Google map 上进行标记聚类

json - 在 Go 中从 POST 请求解码 JSON 失败

cookies - 使用 Golang 登录私有(private)站点并拉取信息

linux - 如何为 GOPATH 使用 Samba 服务器位置?

将一个结构指针转换为另一个 - C

javascript - 实现 Redux 到 React 以从提供的端点返回 JSON 数据

使用 Validator(或类似的东西)进行 python 数据结构验证

java - jackson 自定义号码解析

asp.net-core - Blazor 清理 MarkupString

struct - `==` 是否在 Julia 中递归检查结构?好像没有