登录
首页 >  Golang >  Go问答

在golang中解组json

来源:Golang技术栈

时间:2023-04-12 16:29:29 155浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《在golang中解组json》主要内容涉及到golang等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

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

进入地图[字符串]上下文。

以下是相关定义:

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

type Option struct {
    text string
    arc  string
}

unmarshall 运行没有错误,但是我得到一个带有 Context 结构的 map[intro] ,它的所有内容都初始化为 nils 或空字符串。

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

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

正确答案

对于编组和解组,必须导出字段。

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

文中关于golang的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在golang中解组json》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表