简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM