如何解组具有不同类型值的 JSON 数组

huangapple go评论84阅读模式
英文:

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

问题

例如:

{["纽约",123]}

对于 JSON 数组,它被解码为一个 Go 数组,而 Go 数组需要显式定义类型,我不知道该如何处理。

英文:

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.

答案1

得分: 7

首先,该JSON是无效的,对象必须具有键,所以应该是这样的{"key":["NewYork",123]}或者只是["NewYork",123]

当你处理多个随机类型时,你只需使用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

英文:

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

<kbd>playground</kbd>

答案2

得分: 3

// json包使用map[string]interface{}和[]interface{}值来存储任意的JSON对象和数组...
// http://blog.golang.org/json-and-go

// 对象中的每个值都必须有键。假设这是你的json:
// { "key": ["NewYork", 123] }

// 那么你的代码应该像这样:

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

// 你可以运行它:http://play.golang.org/p/yihj6BZHBY
英文:

> 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 :

{&quot;key&quot;:[&quot;NewYork&quot;,123]}

Then your code should be like this:

package main

import (
	&quot;encoding/json&quot;
	&quot;fmt&quot;
)

type Message map[string]interface{}

func main() {
	msg := Message{}
	s := `{&quot;key&quot;:[&quot;Newyork&quot;,123]}`
	err := json.Unmarshal([]byte(s), &amp;msg)
	fmt.Println(msg, err)
}

You can run it : http://play.golang.org/p/yihj6BZHBY

huangapple
  • 本文由 发表于 2014年8月15日 20:45:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/25326644.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定