dongyi2006 2019-01-05 04:37
浏览 58
已采纳

在Golang中解组json

golang beginner here.

I want to unmarshall some JSON shown here:

 {
  "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"
      }
    ]
  },...}

Into a map[string]Context.

Here are the relevant definitions:

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

type Option struct {
    text string
    arc  string
}

The unmarshall runs without error however I get a map[intro] with the Context struct that has everything initialized to nils or empty strings.

What is the correct way of doing this? The documentation and examples are just really hard to parse for specific use cases.

edit: There is another question that is a possible duplicate but this question is a little different as it requires string tags to be introduced in order to work correctly.

  • 写回答

1条回答 默认 最新

  • douyingzhan5905 2019-01-05 04:59
    关注

    For marshalling and unmarshalling, fields must be exported.

        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"`
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元