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 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题