duanmu5039 2016-05-26 19:46
浏览 23

如何将此嵌套JSON解组到go对象中?

I have a JSON object similar to this one:

{
"prices": {
    "7fb832f4-8041-4fe7-95e4-6453aeeafc93": {
        "diesel": 1.234,
        "e10": 1.234,
        "e5": 1.234,
        "status": "open"
    },
    "92f703e8-0b3c-46da-9948-25cb1a6a1514": {
        "diesel": 1.234,
        "e10": 1.234,
        "e5": 1.234,
        "status": "open"
    }
}

I am not sure how to unmarshal this into an GO object without losing the unique ID field of each sub-item which is important information for me.

  • 写回答

2条回答 默认 最新

  • dsfds4551 2016-05-26 19:50
    关注

    You can use a map with string keys to preserve the unique IDs of each sub-price:

    type Object struct {
        Prices map[string]*Price `json:"prices"`
    }
    
    type Price struct {
        Diesel float32 `json:"diesel"`
        E10    float32 `json:"e10"`
        E5     float32 `json:"e5"`
        Status string  `json:"status"`
    }
    

    Then, for example, you could loop over the unmarshaled object:

    for id, price := range o.Prices {
        fmt.Printf("%s %v
    ", id, price)
    }
    

    https://play.golang.org/p/aPhvGdtFC_

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法