Go中如何解析一个JSON的字段名是一个值?

How to parse a JSON whose field name is a value in Go?

我从服务中收到具有这种格式的 JSON。

{
    "result": {
        "bn05deh7jsm86gtlg2l0C": [
            {
                "index_name": "BASE",
                "index_value": 4081512,
                "timestamp": "2019-11-05T13:20:00Z",
                "op_id": "A0000000001"
            },
            ...
        ],
        "bn05deh7jsm86gtlg2lgC": [
            {
                "index_name": "BASE",
                "index_value": 4728633,
                "timestamp": "2019-11-05T13:20:00Z",
                "op_id": "A0000000001"
            },
            ...
        ],
        ...
    }
}

我需要的是将其转换为对象数组,如 []Measure:

type Measure struct {
    IndexName    string    `json:"index_name"`
    IndexValue   uint32    `json:"index_value"`
    Timestamp    time.Time `json:"timestamp"`
    OperationID  string    `json:"op_id"`
    Guid         string    `json:"guid"`
}

其中 Guid 应具有值 bn05deh7jsm86gtlg2l0Cbn05deh7jsm86gtlg2lgC

这是我的代码:

url := "https://myurl.com"
req, err := http.NewRequest("GET", url, nil)
if req != nil {
    req.Header.Set("Content-Type", "application/json")
}
resp, err := client.Do(req)
if err != nil {
    log.Println(err)
    return nil
}
var measures []Measure
err = json.NewDecoder(resp.Body).Decode(&measures)
if err != nil {
    log.Println(err)
}

我该怎么做?

你不能用普通的 encoding/json 来做到这一点。 Marstall成图[string]测量

解码为与数据结构匹配的类型:

var d struct{ Result map[string][]Measure }
err = json.NewDecoder(resp.Body).Decode(&d)

将该数据转换为所需结果:

var measures []Measure
for k, vs := range d.Result {
    for _, v := range vs {
        v.Guid = k
        measures = append(measures, v)
    }
}

Run it on the playground