dongyan6503 2015-03-31 10:10
浏览 65
已采纳

在go lang中循环/迭代第二层嵌套JSON

Consider the following code:

package main

import (
"encoding/json"
"fmt"
"reflect"
)


func main() {  
    //Creating the maps for JSON
    m := map[string]interface{}{}

    //Parsing/Unmarshalling JSON encoding/json
    err := json.Unmarshal([]byte(input), &m)

    fmt.Println("
Reflect type of Parsing/Unmarshalling Error Object:
",reflect.TypeOf(err))
    fmt.Println("
Parsing/Unmarshalling Error Object:
",err)
    if err != nil {
        panic(err)
    }

    fmt.Println("
Parsed JSON is as follows:
",m)
    fmt.Println("
Reflect type of parsed json object:
", reflect.TypeOf(m))

    for firstLvlkey, firstLvlValue := range m { 
        fmt.Println("First Level Key:", firstLvlkey)
        fmt.Println("First Level Key reflect type of :", reflect.TypeOf(firstLvlkey))

        fmt.Println("First Level Value:", firstLvlValue)
        fmt.Println("First Level Value reflect type of :", reflect.TypeOf(firstLvlValue))
         // <===============================>
         //Here I want to iterate/loop over innerJSON1, InnerJSON2 then reach to level InnerInnerJSONArray - fld1 and fld2
         // <===============================>

    }
}

const input = `
{
    "outterJSON":{
        "innerJSON1":{
            "value1":10,
            "value2":22
            ,
            "InnerInnerArray": [ "test1" , "test2"],
            "InnerInnerJSONArray": [ {"fld1" : "val1"} , {"fld2" : "val2"} ]
            },
            "InnerJSON2":"NoneValue"
        }
    }
    `

I have some requirement like I want to read/get all the Key and value in String type for some processing adn I can't define the struct because I will be getting dynamic JSON input (e.g InnerInnerArray as a string then second level loop will give me index of array and process each JSON having key fld1 and val1).

I wish to iterate over every key/value pair contained within it, what is the most efficient way of going through the map?

Note: I am Newbie for Go-lang, your suggestion/improvement on question is also most welcome.

  • 写回答

3条回答 默认 最新

  • duanjiao5082 2015-04-01 03:06
    关注

    See this blog entry which thoroughly covers this subject, specifically the section Decoding arbitrary data. Using that you can do something like this: (playground example)

    package main
    
    import (
        "encoding/json"
        "fmt"    
    )
    
    func main() {
        // Creating the maps for JSON
        m := map[string]interface{}{}
    
        // Parsing/Unmarshalling JSON encoding/json
        err := json.Unmarshal([]byte(input), &m)
    
        if err != nil {
            panic(err)
        }
        parseMap(m)
    }
    
    func parseMap(aMap map[string]interface{}) {
        for key, val := range aMap {
            switch concreteVal := val.(type) {
            case map[string]interface{}:
                fmt.Println(key)
                parseMap(val.(map[string]interface{}))
            case []interface{}:
                fmt.Println(key)
                parseArray(val.([]interface{}))
            default:
                fmt.Println(key, ":", concreteVal)
            }
        }
    }
    
    func parseArray(anArray []interface{}) {
        for i, val := range anArray {
            switch concreteVal := val.(type) {
            case map[string]interface{}:
                fmt.Println("Index:", i)
                parseMap(val.(map[string]interface{}))
            case []interface{}:
                fmt.Println("Index:", i)
                parseArray(val.([]interface{}))
            default:
                fmt.Println("Index", i, ":", concreteVal)
    
            }
        }
    }
    
    const input = `
    {
        "outterJSON": {
            "innerJSON1": {
                "value1": 10,
                "value2": 22,
                "InnerInnerArray": [ "test1" , "test2"],
                "InnerInnerJSONArray": [{"fld1" : "val1"} , {"fld2" : "val2"}]
            },
            "InnerJSON2":"NoneValue"
        }
    }
    `
    

    This will print:

        //outterJSON
        //innerJSON1
        //InnerInnerJSONArray
        //Index: 0
        //fld1 : val1
        //Index: 1
        //fld2 : val2
        //value1 : 10
        //value2 : 22
        //InnerInnerArray
        //Index 0 : test1
        //Index 1 : test2
        //InnerJSON2 : NoneValue
    

    The key thing is that you have to use type assertion when working with interface types. The type switch makes it easy to determine the type as needed. The code will recursively range through any nested array or map so you can add as many levels as you wish and get all your values.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?