在lang中循环/遍历第二层嵌套的JSON [英] Looping/iterate over the second level nested JSON in go lang

查看:126
本文介绍了在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("\nReflect type of Parsing/Unmarshalling Error Object:\n",reflect.TypeOf(err))
    fmt.Println("\nParsing/Unmarshalling Error Object:\n",err)
    if err != nil {
        panic(err)
    }

    fmt.Println("\nParsed JSON is as follows:\n",m)
    fmt.Println("\nReflect type of parsed json object:\n", 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"
        }
    }
    `

我有一些要求,例如我想要读取/获取 String 类型进行某些处理adn我无法定义 struct ,因为我将获得动态JSON输入(例如 InnerInnerArray 作为一个字符串,然后第二级循环会给我数组的索引并处理每个具有键 fld1 VAL1 )。

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?

注意:我是Go-lang的新手,您对问题的建议/改进也是非常值得欢迎的。

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

推荐答案

请参阅博客文章,详细介绍此主题,尤其是解码任意数据。使用它你可以做这样的事情:
操场示例

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"
    }
}
`

这将打印:

    //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.

这篇关于在lang中循环/遍历第二层嵌套的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆