在Golang中解组json

Bri*_*Yeh -1 json go unmarshalling

golang初学者在这里。

我想解组此处显示的一些JSON:

 {
  "intro": {
    "title": "The Little Blue Gopher",
    "story": [
      "Once upon a time, long long ago, there was a little blue gopher. Our little blue friend wanted to go on an adventure, but he wasn't sure where to go. Will you go on an adventure with him?",
      "One of his friends once recommended going to New York to make friends at this mysterious thing called \"GothamGo\". It is supposed to be a big event with free swag and if there is one thing gophers love it is free trinkets. Unfortunately, the gopher once heard a campfire story about some bad fellas named the Sticky Bandits who also live in New York. In the stories these guys would rob toy stores and terrorize young boys, and it sounded pretty scary.",
      "On the other hand, he has always heard great things about Denver. Great ski slopes, a bad hockey team with cheap tickets, and he even heard they have a conference exclusively for gophers like himself. Maybe Denver would be a safer place to visit."
    ],
    "options": [
      {
        "text": "That story about the Sticky Bandits isn't real, it is from Home Alone 2! Let's head to New York.",
        "arc": "new-york"
      },
      {
        "text": "Gee, those bandits sound pretty real to me. Let's play it safe and try our luck in Denver.",
        "arc": "denver"
      }
    ]
  },...}
Run Code Online (Sandbox Code Playgroud)

进入map [string] Context。

以下是相关定义:

type Context struct {
    title   string
    story   string 
    options *[]Option
}

type Option struct {
    text string
    arc  string
}
Run Code Online (Sandbox Code Playgroud)

取消编组运行没有错误,但是我得到了带有Context结构的map [intro],该结构将所有内容初始化为nils或空字符串。

正确的做法是什么?对于特定的用例,文档和示例确实很难解析。

编辑:还有一个可能重复的问题,但是这个问题有点不同,因为它需要引入字符串标签才能正确工作。

Arc*_*ezy 5

为了进行编组和解组,必须导出字段。

    type Context struct {
        Title   string   `json:"title"`
        Story   string   `json:"story"`
        Options []Option `json:"options"`
    }

    type Option struct {
        Text string `json:"text`
        Arc  string `json:"arc"`
    }
Run Code Online (Sandbox Code Playgroud)

  • 这里的关键是他大写了struct字段。必须将要编组的字段导出。 (3认同)
  • @BrianYeh Go使用大写字母来控制包中字段/结构的导出状态。只有导出的结构和字段对其他包(包括“ encoding / json”包)可见。因此,您必须将结构的字段名称大写以导出这些字段,以使元帅功能可以看到它们。 (3认同)