在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)
}
查看全部
dqzuo0327
dqzuo0327
2018/08/13 03:22
  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复