dongshie8450 2017-09-05 11:23
浏览 33

如何解析不变的json var名称

Could anyone help me parse the following JSON? The tags do not contain "["/"]" brackets, but the left-hand variable names there are indefinite:

Example 1:

{
    "value": 569000000,
    "tags": {
        "importerId": "catchacar",
        "jvmProcess": "12367A"
    }
}

Example 2:

{
    "value": 519,
    "tags": {
        "cluster": "cluster-29042",
        "valueName": "open-files"
    },
    "time": "2017-09-05T11:03:57.877Z"
}

etc

How can I define a struct which catches arbitrary left-hand values ? I have found the following:

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"}},
}

But this produces and needs brackets. Example:

{
  "value": 123,
  "time": "2017-09-01T14:26:33.773Z",
  "tags": [
    {
      "valueName": "valName1",
      "value": "val1"
    }
  ]
}   

Thank you very much !

  • 写回答

1条回答 默认 最新

  • doushijiao0679 2017-09-05 11:43
    关注

    Solution:

    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"},
    }
    

    result:

    {
      "value": 123,
      "time": "2017-09-01T14:26:33.773Z",
      "tags": {
        "bar": "aaa",
        "foo": "aaa"
      }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入