将JSON解析为结构体

huangapple go评论82阅读模式
英文:

Parsing JSON into a struct

问题

我已经成功地将具有常规键值格式的JSON解析为结构体。

然而,我该如何解析这样的JSON:

{
  "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"
    }
  }
}

其中workspaces部分的键不是预先定义的,而是保存了工作区的ID?

我的初始结构体如下:

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

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

我该如何从所示的JSON中获取Workspace列表?

英文:

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

得分: 6

问题在于你在模型中将Workspaces表示为一个数组,但在JSON中它是一个字典/映射。只需将其定义为map[string]Workspace,问题就会解决。你可以通过instance.Workspaces["11"]来获取第一个项目。

我知道这些的一些提示是:1)Workspaces是用大括号{打开的,数组在这种情况下永远不是正确的类型(在JSON中它们总是用[]括起来的),它是一个对象或映射。2)其中的项被表示为"11": { ... }。这意味着如果我在Go中用对象表示它,我需要一个名为1112等的属性,很明显这不是你想要的,所以它必须是一个映射。

英文:

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.

huangapple
  • 本文由 发表于 2015年6月24日 06:54:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/31014838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定