dongru3726 2015-06-23 14:54
浏览 66
已采纳

将JSON解析为结构

I have successfully parsed JSON into structs when they have a regular key-value format.

However, how can I parse a JSON like this:

{
  "count": 2,
  "results": [{ key: "workspaces", id: "10" }, { key: "workspaces", id: "11" }],
  "workspaces": {
    "10": {
      id: "10",
      title: "some project",
      participant_ids: ["2", "6"],
      primary_counterpart_id: "6"
    },
    "11": {
      id: "11",
      title: "another project",
      participant_ids: ["2", "8"],
      primary_counterpart_id: "8"
    }
  }
}

Where the keys for the workspaces section is not defined ahead of time, but instead holds the workspace id?

My initial structs were:

type WorkspaceRequest struct {
    Count      int64       `json:"count"`
    Workspaces []Workspace `json:"workspaces"`
}

type Workspace struct {
    Title string `json:"title"`
}

How can I get a list of Workspaces from the shown JSON?

展开全部

  • 写回答

1条回答 默认 最新

  • douguwo2275 2015-06-23 14:56
    关注

    The problem is that you're representing Workspaces as an array in your model but it's a dictionary/map in the json. Just make it a map[sting]Workspace and you should be good. First item would be had with instance.Workspaces["11"]

    A couple hints as to how I knew that; 1) Workspaces is opened with a brace {, an array is never the right type for this (they always are enclosed by [] in json), it's an object or a map. 2) the items within it are denoted like "11": { ... }. That means if I represent it with an object in Go I need a property named 11, 12 ect, it's pretty safe to assume that's not what you want here meaning it must be a map.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 FPGA芯片60进制计数器
  • ¥15 前端js怎么实现word的.doc后缀文件在线预览
  • ¥20 macmin m 4连接iPad
  • ¥15 DBIF_REPO_SQL_ERROR
  • ¥15 根据历年月数据,用Stata预测未来六个月汇率
  • ¥15 DevEco studio开发工具 真机联调找不到手机设备
  • ¥15 请教前后端分离的问题
  • ¥100 冷钱包突然失效,急寻解决方案
  • ¥15 下载honeyd时报错 configure: error: you need to instal a more recent version of libdnet
  • ¥15 距离软磁铁一定距离的磁感应强度大小怎么求
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部