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 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程