如何将具有两种不同数据类型的 JSON 数组解析为 Golang 中的结构
How to parse JSON arrays with two different data types into a struct in Golang
我有 JSON 看起来像这样:
{
"a": [
[
"12.58861425",
10.52046452
],
[
"12.58861426",
4.1073
]
]
"b": [
[
"12.58861425",
10.52046452
],
[
"12.58861426",
4.1073
]
]
"c": "true"
"d": 1234
}
我想将其解组到我创建的结构中:
type OrderBook struct {
A [][2]float32 `json:"a"`
B [][2]float32 `json:"b"`
C string `json:"c"`
D uint32 `json:"d"`
}
//Note this won't work because the JSON array contains a string and a float value pair rather than only floats.
通常我会把这个 JSON 转换成 Golang 中的结构:
orders := new(OrderBook)
err = json.Unmarshal(JSON, &orders)
因为我无法定义匹配 JSON 的类型结构,所以这行不通。做了一些阅读,我认为 Unmarshal-ing 到一个接口中,然后通过类型检查使用接口数据可能是一个解决方案。
我这样做的方向正确吗?
显示在界面中我如何使用数据的模板真的很有帮助。
为什么不像这样声明 A 和 B 切片的类型呢?
data := []byte(`{"a": [["12.58861425",10.52046452],["12.58861426",4.1073]],"b": [["12.58861425",10.52046452],["12.58861426",4.1073]],"c": "true","d": 1234}`)
type OrderBook struct {
A [][2]interface{} `json:"a"`
B [][2]interface{} `json:"b"`
C string `json:"c"`
D uint32 `json:"d"`
}
orders := new(OrderBook)
err := json.Unmarshal(data, &orders)
if err != nil {
fmt.Printf(err.Error())
} else {
fmt.Printf("%s\n", orders.A[0][0].(string))
fmt.Printf("%f\n", orders.A[0][1].(float64))
}
操场上有一个例子:https://play.golang.org/p/0MUY-yOYII
我必须不同意 evanmcdonnal,当然有一些用例,其中滚动你自己的 Unmarshaller 是有意义的,我认为这不是其中之一。它并没有比这里显示的更简单。
我有 JSON 看起来像这样:
{
"a": [
[
"12.58861425",
10.52046452
],
[
"12.58861426",
4.1073
]
]
"b": [
[
"12.58861425",
10.52046452
],
[
"12.58861426",
4.1073
]
]
"c": "true"
"d": 1234
}
我想将其解组到我创建的结构中:
type OrderBook struct {
A [][2]float32 `json:"a"`
B [][2]float32 `json:"b"`
C string `json:"c"`
D uint32 `json:"d"`
}
//Note this won't work because the JSON array contains a string and a float value pair rather than only floats.
通常我会把这个 JSON 转换成 Golang 中的结构:
orders := new(OrderBook)
err = json.Unmarshal(JSON, &orders)
因为我无法定义匹配 JSON 的类型结构,所以这行不通。做了一些阅读,我认为 Unmarshal-ing 到一个接口中,然后通过类型检查使用接口数据可能是一个解决方案。
我这样做的方向正确吗?
显示在界面中我如何使用数据的模板真的很有帮助。
为什么不像这样声明 A 和 B 切片的类型呢?
data := []byte(`{"a": [["12.58861425",10.52046452],["12.58861426",4.1073]],"b": [["12.58861425",10.52046452],["12.58861426",4.1073]],"c": "true","d": 1234}`)
type OrderBook struct {
A [][2]interface{} `json:"a"`
B [][2]interface{} `json:"b"`
C string `json:"c"`
D uint32 `json:"d"`
}
orders := new(OrderBook)
err := json.Unmarshal(data, &orders)
if err != nil {
fmt.Printf(err.Error())
} else {
fmt.Printf("%s\n", orders.A[0][0].(string))
fmt.Printf("%f\n", orders.A[0][1].(float64))
}
操场上有一个例子:https://play.golang.org/p/0MUY-yOYII
我必须不同意 evanmcdonnal,当然有一些用例,其中滚动你自己的 Unmarshaller 是有意义的,我认为这不是其中之一。它并没有比这里显示的更简单。