dt614037527 2017-02-21 22:03
浏览 161

map [string]结构体中的结构体

I have a JSON file that looks like this:

{
  "jailbreaks": [
    {
      "jailbroken": false,
      "name": "",
      "version": "",
      "url": "",
      "anleitung": [],
      "ios": {
        "start": "10.2.1"
      },
      "caveats": "",
      "platforms": []
    },
    {
      "jailbroken": true,
      "name": "Yalu102",
      "version": "beta 6",
      "url": "https://domain-dl.tld",
      "anleitung": [
        { "blog": "title", "link": "http://domain.tld/" },
        { "blog": "Test", "link": "http://google.at" }
      ],
      "ios": {
        "start": "10.2"
      },
      "caveats": "some text here",
      "platforms": [
        "Windows",
        "OS X",
        "Linux"
      ]
    },

And I create the object to work with like this:

type Jailbreak struct {
    Jailbroken bool   `json:"jailbroken"`
    Name       string `json:"name"`
    Version    string `json:"version"`
    URL        string `json:"url"`
    Anleitung  map[string]struct {
        Name string `json:"blog"`
        Link string `json:"link"`
    } `json:"anleitung"`

    Firmwares struct {
        Start string `json:"start"`
        End   string `json:"end"`
    } `json:"ios"`

    Platforms []string `json:"platforms"`
    Caveats   string   `json:"caveats"`
}

When I want to build my go program I get an error, that the JSON file cannot be read. But as soon as I delete the map[string]struct I can compile and run the program without any error and everything works fine. Am I messing around with something or is there an error in my JSON file?

  • 写回答

2条回答 默认 最新

  • dpzbh1779 2017-02-21 22:22
    关注

    Use omitempty flag for when your "anleitung" is empty in JSON to be consumed. Beware though, when that is the case, your Jailbreak struct won't have an "anleitung" field.

    Change your map's json flag to to;

    Anleitung   map[string]struct {
        Name string `json:"blog"`
        Link string `json:"link"`
    } `json:"anleitung,omitempty"`
    

    Option 2;

    I guess you could also use Anleitung map[string]interface{} but that is better for "holding a map of strings to arbitrary data types". In your case the data is not arbitrary but rather, empty I guess. And looks like that is just temporary.

    I'd go for option 1, then I'd check if my struct contains any Anleitung data or not before accessing it.

    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办