0

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 Answer 1

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.

1
  • Thank you so much. When you answered, it became obvious. But the same is true for almost all hard problems :)
    – kolrie
    Commented Jun 23, 2015 at 23:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.