如何解组一个具有不同类型值的json数组 [英] How to unmarshal a json array with different type of value in it

查看:454
本文介绍了如何解组一个具有不同类型值的json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

For example:

{["NewYork",123]}

对于json数组,解码为一个go数组,并且数组需要显式定义一个类型,
我不知道如何处理它。

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.

推荐答案

首先,json无效,对象必须有键,所以它应该像 {key:[NewYork,123]} 或者只是 [NewYork,123]

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

当你处理多个随机类型时,只需使用 interface {}

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

这篇关于如何解组一个具有不同类型值的json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆