Jeffail/gabs

Iterating keys using Children or Children map

Closed this issue · 2 comments

In the following example


import (
	"fmt"
	"github.com/Jeffail/gabs/v2"
)

func main() {
	src := []byte(`{"0": {"Name": "Mr. Michael R. McMullen", "Title": "CEO, Pres & Director", "YearBorn": "1961"}, "1": {"Name": "Mr. Robert W. McMahon", "Title": "Sr. VP & CFO", "YearBorn": "1969"}, "2": {"Name": "Mr. Michael  Tang", "Title": "Sr. VP, Gen. Counsel & Sec.", "YearBorn": "1974"}, "3": {"Name": "Mr. Mark  Doak", "Title": "Sr. VP & Pres of Agilent Cross Lab Group", "YearBorn": "1955"}, "4": {"Name": "Mr. Jacob  Thaysen", "Title": "Sr. VP and Pres of Life Sciences & Applied Markets Group", "YearBorn": "1975"}}`)
	parsed, err := gabs.ParseJSON(src)
	if err != nil {
		fmt.Printf("err \n")
	}
       
        // Does not work
	for key := range parsed.Children() {
		string1 := string(key)
		fmt.Printf("key: %v, name: %v\n", key, parsed.S(string1))
	}
	
	// Does work
	for key := range parsed.ChildrenMap() {
		string1 := string(key)
		fmt.Printf("key: %v, name: %v\n", key, parsed.S(string1))
	}

}

The call to Children returns each key like ChildrenMap. But only ChildrenMap do the indices actually work to access the underlying information.
Why is this?
And thank you for the great package!

Output from the program

key: 0, name: null
key: 1, name: null
key: 2, name: null
key: 3, name: null
key: 4, name: null
key: 4, name: {"Name":"Mr. Jacob  Thaysen","Title":"Sr. VP and Pres of Life Sciences \u0026 Applied Markets Group","YearBorn":"1975"}
key: 0, name: {"Name":"Mr. Michael R. McMullen","Title":"CEO, Pres \u0026 Director","YearBorn":"1961"}
key: 1, name: {"Name":"Mr. Robert W. McMahon","Title":"Sr. VP \u0026 CFO","YearBorn":"1969"}
key: 2, name: {"Name":"Mr. Michael  Tang","Title":"Sr. VP, Gen. Counsel \u0026 Sec.","YearBorn":"1974"}
key: 3, name: {"Name":"Mr. Mark  Doak","Title":"Sr. VP \u0026 Pres of Agilent Cross Lab Group","YearBorn":"1955"}

Hey @nathanmalishev, the call to Children returns an array of values from your target object, the variable key you're setting is actually an integer index of the returned array. In order to get values you'd need to do this:

	src := []byte(`{"0": {"Name": "Mr. Michael R. McMullen", "Title": "CEO, Pres & Director", "YearBorn": "1961"}, "1": {"Name": "Mr. Robert W. McMahon", "Title": "Sr. VP & CFO", "YearBorn": "1969"}, "2": {"Name": "Mr. Michael  Tang", "Title": "Sr. VP, Gen. Counsel & Sec.", "YearBorn": "1974"}, "3": {"Name": "Mr. Mark  Doak", "Title": "Sr. VP & Pres of Agilent Cross Lab Group", "YearBorn": "1955"}, "4": {"Name": "Mr. Jacob  Thaysen", "Title": "Sr. VP and Pres of Life Sciences & Applied Markets Group", "YearBorn": "1975"}}`)
	parsed, err := gabs.ParseJSON(src)
	if err != nil {
		panic(err)
	}
       
	for i, value := range parsed.Children() {
		fmt.Printf("index: %v, value: %v\n", i, value)
	}

This method is normally only for arrays within your JSON object.

Thanks @Jeffail , thats clear!