douhui2307 2016-11-09 11:03
浏览 42
已采纳

未知密钥无法解组嵌套json

I am having trouble unmarshalling a json data of the below format to a struct. The structure of the json looks a bit confusing to me, so apologies for all the dumb things I am doing to unmarshal it.

{
  "message": {
    "Server1.example.com": [
      {
        "application": "Apache", 
        "host": {
          "name": "/^Server-[13456]/"
        }, 
        "owner": "User1", 
        "project": "Web", 
        "subowner": "User2"
      }
    ], 
    "Server2.example.com": [
      {
        "application": "Mysql", 
        "host": {
          "name": "/^Server[23456]/"
        }, 
        "owner": "User2", 
        "project": "DB", 
        "subowner": "User3"
      }
    ] 
  }, 
  "response_ms": 659, 
  "success": true
}

I am trying to unmarshal it using the following struct.

type ServerDetails struct  {
  Message  struct{
    Hostname struct{
      Details struct{
        Application string `json:"application"`
        }`json:"-"`
       }`json:"-"`
     }`json:"message"`
}

The fields Server[0-9].example.com will be unknown at the time of generating, and will change, and there is this field

      {
    "application": "Apache", 
    "host": {
      "name": "/^Server-[13456]/"
    },

just after the server name that doesn't have a key outside, which again looks confusing to me. I tried a good number of combinations to understand how this could be unmarshalled, but I failed.

What is a working approach to get the json fields unmarshal into a struct?

  • 写回答

2条回答 默认 最新

  • dongwo5686 2016-11-09 14:39
    关注

    You could include a map[string]ServerStruct to fullfill your requirements.

    your struct could look like this:

    type YourStruct struct {
        Success bool
        ResponseMS int
        Servers map[string]*ServerStruct
    }
    
    type ServerStruct struct {
        Application string
        Owner string
        [...]
    }
    

    With some additional json tags, you will be able to parse your json.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配