有人可以帮我解析下面的JSON吗?标签不包含“[”/“]”括号,但左侧变量名称不确定:
示例1:
{
"value": 569000000,
"tags": {
"importerId": "catchacar",
"jvmProcess": "12367A"
}
}
示例2:
{
"value": 519,
"tags": {
"cluster": "cluster-29042",
"valueName": "open-files"
},
"time": "2017-09-05T11:03:57.877Z"
}
等
如何定义捕获任意左手值的结构?我找到了以下内容:
type JSONTag struct {
ValueName string `json:"valueName"` <--- what to write here ????
Value string `json:"value"`
}
type JSONMessage struct {
Value float64 `json:"value"`
Time string `json:"time"`
Tags []JSONTag `json:"tags"`
}
group := JSONMessage{
Value: 123,
Time: "2017-09-01T14:26:33.773Z",
Tags: []JSONTag{JSONTag{"valName1", "val1"}},
}
但这会产生并需要括号。例如:
{
"value": 123,
"time": "2017-09-01T14:26:33.773Z",
"tags": [
{
"valueName": "valName1",
"value": "val1"
}
]
}
非常感谢!
答案 0 :(得分:0)
解决方案:
type JSONTag struct {
ValueName string `json:"valueName"`
Value string `json:"value"`
}
type JSONMessage struct {
Value float64 `json:"value"`
Time string `json:"time"`
Tags map[string]string `json:"tags"`
}
...
// usage:
group := JSONMessage{
Value: 123,
Time: "2017-09-01T14:26:33.773Z",
Tags: map[string]string{"foo": "aaa", "bar": "aaa"},
}
结果:
{
"value": 123,
"time": "2017-09-01T14:26:33.773Z",
"tags": {
"bar": "aaa",
"foo": "aaa"
}
}