当JSON字段键是日期时,如何将JSON对象解组为Golang结构



我有以下JSON响应。将其分解为Golang结构的最佳方法是什么?JSON到Golang自动生成的结构表示该结构的命名属性应为20210712、20210711、20210710等,但这不起作用,因为随着未来日期的变化,结构字段将有所不同。动态地做到这一点的最佳方式是什么?

{
"data": {
"2021-07-12": {
"Neutral": 3,
"Positive": 4,
"Negative": 4
},
"2021-07-11": {
"Neutral": 0,
"Positive": 1,
"Negative": 4
},
"2021-07-10": {
"Neutral": 0,
"Positive": 0,
"Negative": 3
}
}
}

您可以使用地图:

type Item struct {
Neutral int
Positive int
Negative int
}
type Data struct {
Data map[string]Item `json:"data"`
}

解组时,可以使用data.Data["2021-07-11"]

根据Burak Serdar的输入,我为您的场景创建了一个简单的程序,如下所示:

package main
import (
"encoding/json"
"fmt"
)
type Item struct {
Neutral  int
Positive int
Negative int
}
type Data struct {
Data map[string]Item `json:"data"`
}
func main() {
var resData Data
var data = []byte(`{
"data":{
"2021-07-12":{
"Neutral":3,
"Positive":4,
"Negative":4
},
"2021-07-11":{
"Neutral":0,
"Positive":1,
"Negative":4
},
"2021-07-10":{
"Neutral":0,
"Positive":0,
"Negative":3
}
}
}`)
if err := json.Unmarshal(data, &resData); err != nil {
panic(err)
}
fmt.Println(resData)
fmt.Println(resData.Data["2021-07-10"])
}

输出:

{map[2021-07-10:{0 0 3} 2021-07-11:{0 1 4} 2021-07-12:{3 4 4}]}
{0 0 3}

最新更新