dqzuo0327 2018-08-13 03:22
浏览 120
已采纳

在Golang中迭代列表json对象

I have this piece of code to read a json object. I need to easily iterate over all the elements in the 'outputs'/data/concepts key.

Is there a better way to do it?

ALso, how can I access the attributes of value. ie; value.app_id, value.id..etc

Code

package main

import (
    "encoding/json"
    "fmt"
)

var jsonBytes = []byte(`
{"outputs": [{
          "data": {"concepts": 
                                 [{"app_id": "main",
                                     "id": "ai_GTvMbVGh",
                                     "name": "ancient",
                                     "value": 0.99875855}]
              }}
              ],
 "status": {"code": 10000, "description": "Ok"}}`)


func main() {
    var output map[string]interface{}
    err := json.Unmarshal([]byte(jsonBytes), &output)
    if err != nil {
        print(err)
    }
    for _, value := range output["outputs"].([]interface{}) {
        //fmt.Println(value.(map[string]interface{})["data"].(map[string]interface{})["concepts"]).([]interface{})
        //fmt.Println(value.(map[string]interface{})["data"].(map[string]interface{})["concepts"])
        for _, value := range value.(map[string]interface{})["data"].(map[string]interface{})["concepts"].([]interface{}){
            fmt.Println(value)
        }
    }
    //fmt.Printf("%+v
", output)
}
  • 写回答

1条回答 默认 最新

  • doubi9999 2018-08-13 04:08
    关注

    the best way will be to Unmarshal the JSON into an struct and iterate over the values,

    func main() {
    
            var output StructName
    
    
    err := json.Unmarshal([]byte(jsonBytes), &output)
        if err != nil {
            print(err)
        }
        for _, value := range output.Outputs {
            for _, val := range value.Data.Concepts {
                fmt.Printf("AppId:%s
    ID:%s
    name:%s
    value:%f", val.AppID, val.ID, val.Name, val.Value)
            }
        }
    }
    
    type StructName struct {
        Outputs []struct {
            Data struct {
                Concepts []struct {
                    AppID string  `json:"app_id"`
                    ID    string  `json:"id"`
                    Name  string  `json:"name"`
                    Value float64 `json:"value"`
                } `json:"concepts"`
            } `json:"data"`
        } `json:"outputs"`
        Status struct {
            Code        int    `json:"code"`
            Description string `json:"description"`
        } `json:"status"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于c++外部库文件宏的问题,求解
  • ¥15 office打开卡退(新电脑重装office系统后)
  • ¥300 FLUENT 火箭发动机燃烧EDC仿真
  • ¥15 【Hadoop 问题】Hadoop编译所遇问题hadoop-common: make failed with error code 2
  • ¥15 vb6.0+webbrowser无法加载某个网页求解
  • ¥15 RPA财务机器人采购付款流程
  • ¥15 计算机图形多边形及三次样条曲线绘制
  • ¥15 根据protues画的图用keil写程序
  • ¥200 如何使用postGis实现最短领规划?
  • ¥15 pyinstaller打包错误