dongru3726
dongru3726
2015-06-23 22:54

将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 douguwo2275 6年前

    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.

    点赞 评论 复制链接分享