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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大