How to Efficiently Iterate Through Nested JSON in Go?

Patricia Arquette
Release: 2024-11-26 10:46:11
Original
584 people have browsed it

How to Efficiently Iterate Through Nested JSON in Go?

Looping/Iterating Over Second Level Nested JSON in Go Lang

Consider the scenario where you encounter a nested JSON structure like the one depicted below:

{
    "outterJSON": {
        "innerJSON1": {
            "value1": 10,
            "value2": 22,
            "InnerInnerArray": [ "test1" , "test2"],
            "InnerInnerJSONArray": [ {"fld1" : "val1"} , {"fld2" : "val2"} ]
        },
        "InnerJSON2":"NoneValue"
    }
}
Copy after login

The task is to effectively iterate through this structure and retrieve all key-value pairs as strings for further processing. Unfortunately, manually defining a struct for such a dynamic JSON input is not feasible.

Efficient Iteration Approach

To navigate this challenge efficiently, a recursive approach is employed:

func parseMap(m map[string]interface{}) {
  for key, val := range m {
    // Check the type of the value
    switch concreteVal := val.(type) {
      case map[string]interface{}:
        // If it's a nested map, recursively call the function
        parseMap(val.(map[string]interface{}))
      case []interface{}:
        // If it's a nested array, call the function to parse the array
        parseArray(val.([]interface{}))
      default:
        // For all other types, print the key and value as a string
        fmt.Println(key, ":", concreteVal)
    }
  }
}
Copy after login

This recursive function parseMap examines the type of each value in the map. If the value is itself a map, it recursively calls parseMap to traverse that nested map. If the value is an array, it calls parseArray to iterate over it. For all other types (such as strings, numbers, etc.), it simply prints the key and value as a string.

Demo

Consider the example JSON input provided earlier. Running the code below will produce the following output:

func parseArray(a []interface{}) {
  for i, val := range a {
    // Check the type of the value
    switch concreteVal := val.(type) {
      case map[string]interface{}:
        // If it's a nested map, recursively call the function
        parseMap(val.(map[string]interface{}))
      case []interface{}:
        // If it's a nested array, call the function to parse the array
        parseArray(val.([]interface{}))
      default:
        // For all other types, print the index and value as a string
        fmt.Println("Index:", i, ":", concreteVal)
    }
  }
}

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

Output:

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

This approach effectively captures all key-value pairs within the nested JSON, making it suitable for processing and extraction tasks in Go lang.

The above is the detailed content of How to Efficiently Iterate Through Nested JSON in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template