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

后端 未结 2 1431
轮回少年
轮回少年 2020-12-19 15:59

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 Ho

相关标签:
2条回答
  • 2020-12-19 16:07

    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

    0 讨论(0)
  • 2020-12-19 16:18

    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

    0 讨论(0)
提交回复
热议问题