【问题标题】:How to parse a JSON whose field name is a value in Go? [duplicate]如何解析字段名称为 Go 中的值的 JSON? [复制]
【发布时间】:2020-03-03 04:55:06
【问题描述】:

我从服务收到具有这种格式的 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)
}

我该怎么做?

【问题讨论】:

    标签: json rest go decode


    【解决方案1】:

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

    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

    【讨论】:

    • @Adrian:哦,对了。 ://
    • 第一个代码块中有一个错字,Decode(&measures) 应该是Decode(&d) 以适应示例。
    【解决方案2】:

    您无法使用纯编码/json 执行此操作。编入地图[string]Measure

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 2012-08-30
      • 2016-09-01
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      相关资源
      最近更新 更多