英文:
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)
}
英文:
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)
}
答案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 :
{"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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论