How to unmount json array with different value type in it

For example:

{["NewYork",123]}

      

For json array is decoded as go array, and go array needs to be explicitly type specified.I don't know how to deal with this.

+3


source to share


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)
}

      

playground

+7


source


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







All Articles