Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unmarshal a json array with different type of value in it

Tags:

json

go

For example:

{["NewYork",123]}

For json array is decoded as a go array, and go array is need to explicit define a type, I don't know How to deal with it.

like image 208
tomsawyer Avatar asked Dec 26 '22 05:12

tomsawyer


1 Answers

First that json is invalid, objects has to have keys, so it should be something like {"key":["NewYork",123]} or just ["NewYork",123].

And when you're dealing with multiple random types, you just use interface{}.

const j = `{"NYC": ["NewYork",123]}`

type UntypedJson map[string][]interface{}

func main() {
    ut := UntypedJson{}
    fmt.Println(json.Unmarshal([]byte(j), &ut))
    fmt.Printf("%#v", ut)
}

playground

like image 50
OneOfOne Avatar answered May 06 '23 09:05

OneOfOne