Sredny M Casanova
Sredny M Casanova

Reputation: 5053

Loop over Json using Golang go-simplejson

I am working in Golang,and using the package github.com/bitly/go-simplejson

I will receive a Json from the client side, I already constructed the json object using that package. Now I need to iterate over all the "first level" elements of that Json. The Json is something like this:

{"Name":"demo2","Creator":"some creator","URL":"www.url.com","GACode":"UA-xxxx"} 

My code is:

body, _ := ioutil.ReadAll(req.Body)
settings,_ := simplejson.NewJson(body)
fmt.Printf("\nJson: %+v",settings)

for k, v := range settings.MustArray() {
    fmt.Println("\n k:",k)
    fmt.Println("\n v:",v)
}

When I print the Json I receive:

Json: &{data:map[Name:demo2 Creator:some creator URL:www.url.com GACode:UA-xxxx]}

And the loop is giving me nothing, MustArray() is giving me an empty array. The keys of that Json are very dynamic so I cannot do somehting like .Get("TheKey") because I don't know the name of the keys that can come in the json.

Then, how can I loop over that Json? I am more insterested in loop over the first level of that Json.

Upvotes: 1

Views: 3256

Answers (1)

mkopriva
mkopriva

Reputation: 38203

In Go you can use the range loop to iterate over a map the same way you would over an array or slice. The values provided to you by the range loop on each iteration will be the map's keys and their corresponding values.

So you can simply change your loop line from:

for k, v := range settings.MustArray() {

To:

for k, v := range settings.MustMap() {

Also, personally, I would recommend ditching simplejson unless you have a better use case for it than what you have in your example. Using the standard encoding/json you can achieve the same result with less effort in my opinion.

var settings map[string]interface{}
if err := json.NewDecoder(req.Body).Decode(&settings); err != nil {
    panic(err)
}
fmt.Printf("\nJson: %+v",settings)

for k, v := range settings {
    fmt.Println("\n k:",k)
    fmt.Println("\n v:",v)
}

Example on playground: https://play.golang.org/p/TKdO5pOJCY

More info on for with range here: https://golang.org/ref/spec#For_range

Upvotes: 3

Related Questions