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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵