2

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: 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\n", output)
}
2
  • your json is invalid. Commented Aug 13, 2018 at 3:31
  • oops.fixed the data and the code. Need to know if there is a better way to iterate. Commented Aug 13, 2018 at 3:57

1 Answer 1

3

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\nID:%s\nname:%s\nvalue:%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"`
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.