我目前有一个大型JSON文件,必须存储在后端(mongodb& Go)并在前端使用。我想知道文档的第3个字段是否应该像“子类别”而不是第2个字段中的运动名称,或者这是否可能,因为我认为这可能很难用后端语言建模和反序列化由于不一致?
样品:
{
"_id" : ObjectId("55c"),
"Sport" : "Athletics ",
"Athletics" : {
["Men's Individual", "Women's Individual", "Mixed Relay"]
}
}
{
"_id" : ObjectId("56c"),
"Sport" : "Tennis",
"Tennis" : ["Men's singles", "Women's singles", "Men's doubles", "Women's doubles", "Mixed doubles"]
}
{
"_id" : ObjectId("57c"),
"Sport" : "Swimming",
"Swimming" : {
"Men" : ["4×100 m relay", "4×200 m freestyle relay"],
"Women" : ["4×100 m relay", "4×200 m freestyle relay"]
}
}
答案 0 :(得分:3)
我同意这个小声音告诉你要使用“子类别”,而不是试图处理不一致的类型。此外,您应该将游泳中的“男性”和“女性”子类别与网球和田径运动中的“男性”和“女性”子类别相结合。这将让你更好地利用encoding / json(和mgo / bson)的映射功能,但我不会称之为'后端语言'问题 - 一致的数据类型应该使你的js(和其他客户端代码)更好!
答案 1 :(得分:2)
您可以使用json.RawMessage
执行此操作:
package main
import (
"encoding/json"
"fmt"
"log"
)
func main() {
type Color struct {
Space string
Point json.RawMessage // delay parsing until we know the color space
}
type RGB struct {
R uint8
G uint8
B uint8
}
type YCbCr struct {
Y uint8
Cb int8
Cr int8
}
var j = []byte(`[
{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
{"Space": "RGB", "Point": {"R": 98, "G": 218, "B": 255}}
]`)
var colors []Color
err := json.Unmarshal(j, &colors)
if err != nil {
log.Fatalln("error:", err)
}
for _, c := range colors {
var dst interface{}
switch c.Space {
case "RGB":
dst = new(RGB)
case "YCbCr":
dst = new(YCbCr)
}
err := json.Unmarshal(c.Point, dst)
if err != nil {
log.Fatalln("error:", err)
}
fmt.Println(c.Space, dst)
}
}