tomsawyer
tomsawyer

Reputation: 105

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

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.

Upvotes: 5

Views: 4496

Answers (2)

Halil Bilgin
Halil Bilgin

Reputation: 513

The json package uses map[string]interface{} and []interface{} values to store arbitrary JSON objects and arrays... http://blog.golang.org/json-and-go

Each value in an object must have key. So suppose this is your json :

{"key":["NewYork",123]}

Then your code should be 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

Upvotes: 3

OneOfOne
OneOfOne

Reputation: 99234

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

Upvotes: 8

Related Questions