[英]Best way to represent this JSON in Go?
我正在编写一个端点以返回Geckoboard的数据,但它的格式如下:
{
"item": [
{
"value": "274057"
},
[
"38594",
"39957",
"35316",
"35913",
"36668",
"45660",
"41949"
]
]
}
"item"
是各种结构的数组。 我将如何在Go中表示这些数据?
注意:这与我如何解组无关,我需要生成此格式。
这些东西比您想象的要容易。 对于随便的读者来说,它的文档还不够完善。 我会推荐ffjson
不是普通的json
tho。 它的构成方式是您无需更改库名称以外的语法。
这很容易:
type User struct {
Id int `json:'id'`
Name string `json:name`
SomeId1 int `json:some_id_1`
SomeId2 int `json:some_id_2`
SomeId3 int `json:some_id_3`
SomeId4 int `json:some_id_4`
}
item := map[string]User{}
for i := 0; i < 10; i++ {
item[strconv.itoa(i)] = User{i, "Username X", 38393, 29384, 12393, 123981}
}
buf, err := ffjson.Marshal(&item)
结构的缺点(即使在ffjson
也是如此)将始终使用reflection
,这在您需要高性能的时候,您将浪费大量的CPU周期。 ffjson
保留在地图上时,它的速度是普通json
2-3倍。 这样,库可以编译您封送的每个数据结构并重新使用它,而不用不断地用reflect
检查数据完整性/结构。
有一种简单的方法可以创建某些数据结构的值,您知道要生成/复制的JSON输出:
取得要生成的输出,并将其解组到map[string]interface{}
。 您将获得一个地图值,当您进行编组时将产生所需的输出。 解组预期的输出时,可以检查结果映射值以知道需要创建什么才能获得预期的输出。
这也适用于您的情况。 这是代码:
var m map[string]interface{}
err := json.Unmarshal([]byte(input), &m)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", m)
res, err := json.MarshalIndent(m, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(res))
input
是您的JSON输入:
const input = `{
"item": [
{
"value": "274057"
},
[
"38594",
"39957",
"35316",
"35913",
"36668",
"45660",
"41949"
]
]
}`
该程序生成与所需输出(或输入)相同的输出:
map[item:[map[value:274057] [38594 39957 35316 35913 36668 45660 41949]]]
{
"item": [
{
"value": "274057"
},
[
"38594",
"39957",
"35316",
"35913",
"36668",
"45660",
"41949"
]
]
}
在Go Playground上尝试完整的应用程序。
显然,它具有键"item"
,其值的类型为:
fmt.Printf("%T\n", m["item"]); // Prints []interface{}
所以这是片。 它具有2个值,它们的类型为:
fmt.Printf("%T\n", m["item"].([]interface{})[0]); // map[string]interface{}
fmt.Printf("%T\n", m["item"].([]interface{})[1]); // []interface{}
因此,切片包含2个值:
"value" : "274057"
对) 这是复制相同地图值的Go代码:
m := map[string]interface{}{
"item": []interface{}{
map[string]interface{}{"value": "274057"},
[]interface{}{"38594", "39957", "35316", "35913", "36668", "45660", "41949"},
},
}
封送处理将产生相同的JSON输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.