dongyan8929 2019-09-02 21:19
浏览 44
已采纳

用不同的键解组相同的json对象去切片结构

I can't figure out how I can serialize the same JSON object with a different key to Go slice struct without re-writing entire parser. For example, JSON that I can receive back, it might contain N number object with a different key (localhost1/localhost2/localhost3, etc). In this example, I have a key localhost1/localhost2/localhost3, and each has only one field ok.

{
"stats": {
        "localhost1": {
            "ok": 1
        },
        "localhost2": {
            "ok": 1
        },
        "localhost3": {
            "ok": 1
        }
     }
}

I can Unmarsh entire JSON by using the following Structs mappings.

type HostStatus struct {
        Ok int `json:"ok"`
}

type Test struct {
    Stats struct {
        Localhost1 HostStatus `json:"localhost1"`
        Localhost2 HostStatus `json:"localhost2"`
        Localhost3 HostStatus `json:"localhost3"`
    }  `json:"stats"`
}

Entire Example.

package main

import (
    "encoding/json"
    "fmt"
)
type HostStatus struct {
        Ok int `json:"ok"`
}

type Test struct {
    Stats struct {
        Localhost1 HostStatus `json:"localhost1"`
        Localhost2 HostStatus `json:"localhost2"`
        Localhost3 HostStatus `json:"localhost3"`
    }  `json:"stats"`
}


func main() {
    var resp = []byte(`{
        "stats": {
            "localhost1": {
            "ok": 1
        },
        "localhost2": {
            "ok": 1
        },
        "localhost3": {
            "ok": 1
        }
        }
    }`)

    var r Test
    er := json.Unmarshal(resp, &r)
    if er != nil {
        panic(er)
    } else {
        fmt.Println(r)
    }
}

The main issue in this solution that it requires hardcode inside a Stats struct each HostStatus that maps 1:1 to JSON output via json:xxx tag. But I want to find a way to map all this object to a HostStatus slice/array since I don't know how many HostStatus objects I might receive back and what is the key for each.

For example something like

type Test struct {
    Stats struct {
        LocalHostList []HostStatus `json:"localhost[0-9]"`
    }  `json:"stats"`
}

and use something like localhost[0-9] -- i.e regex semantics that will give a hit to JSON package.

  • 写回答

1条回答 默认 最新

  • douciwang6819 2019-09-02 21:22
    关注

    Try this:

    type Test struct {
        Stats map[string]HostStatus `json:"stats"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加