dqzuo0327
2018-08-13 03:22 阅读 89
已采纳

在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 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"`
    }
    
    点赞 评论 复制链接分享

相关推荐