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" } }
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.
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) } } }
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.
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" } } `
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
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!