How to unmount json array with different value type in it
2 answers
First that json is not valid, objects must have keys, so it must be something like {"key":["NewYork",123]}
or simple ["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)
}
+7
source to share
The json package uses the [string] interface {} and [] interface {} interface values to store arbitrary JSON objects and arrays ... http://blog.golang.org/json-and-go
Each object value must have a key. Let's assume this is your json:
{"key":["NewYork",123]}
Then your code should look something like this:
package main
import (
"encoding/json"
"fmt"
)
type Message map[string]interface{}
func main() {
msg := Message{}
s := `{"key":["Newyork",123]}`
err := json.Unmarshal([]byte(s), &msg)
fmt.Println(msg, err)
}
You can run it: http://play.golang.org/p/yihj6BZHBY
+3
source to share