Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding JSON in Go without all key names

I'm new to Go and am trying to decode a json blob via feeding structs to Unmarshal. Trouble is, I dont know certain keys. I can parse the following

{"age":21,"Travel":{"fast":"yes","sick":false} }

like so

type user struct {
    Age int
    Travel TravelType
}

type TravelType struct {
    Fast string
    Sick bool
}


func main() {
    src_json := []byte(`{"age":21,"travel":{"fast":"yes","sick":false}}`)
    u := user{}
    err := json.Unmarshal(src_json, &u)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v", u)

}

to obtain {21 {yes false}}

However, I dont see how I would approach something like this-

{
  "age":21,
  "Travel":
     {
         "canada":
         {"fast":"yes","sick":false}, 
         "bermuda": 
         {"fast":"yes","sick":false}, 
         "another unknown key name":
         {"fast":"yes","sick":false},
     }
}

without explictly declaring "Canada", "Bermuda", etc in structs. How could I use Unmarshal to parse the above json? I found this answer, but dont see how it might be implemented

like image 636
rocketas Avatar asked Feb 17 '14 01:02

rocketas


1 Answers

You can Unmarshal into a map[string]TravelType. Change your user struct to this and you should be good to go:

type user struct {
        Age    int
        Travel map[string]TravelType
}

Here's a working proof-of-concept on the Go Playground: http://play.golang.org/p/-4k9GE5ZlS

like image 170
pauljz Avatar answered Oct 22 '22 13:10

pauljz