json - 如何为 json 创建正确的结构

标签 json go

如何正确解析json 我有如下json文件

{
    "hello": {
        "title": "Golang",
        "story": [
            "Go lang story",
            "Channel story"
        ],
        "options": [
            {
                "text": "That story",
                "arc": "west"
            },
            {
                "text": "Gee",
                "arc": "east"
            }
        ]
    },
    "world": {
        "title": "Visiting",
        "story": [
            "Boo",
            "Doo",
            "Moo",
            "Qoo"
        ],
        "options": [
            {
                "text": "weird",
                "arc": "west"
            },
            {
                "text": "funny",
                "arc": "north"
            }
        ]
    }
}

我已经为内部创建了这些结构

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

type option struct {
    Text string `json:"text"`
    Arc string `json:"arc"`
}

但我不知道如何解析像“hello”和“world”这样的包装器

最佳答案

所有你需要做的构建根映射。

{
    "hello":{},
    "world":{}
}

这里 helloworld 也在 map 中。所以你也需要构建它们。

 var root map[string]chapter
 json.Unmarshal(JSONDATA,&root)

Playground 示例:https://play.golang.org/p/VZ9Bn215dDW

关于json - 如何为 json 创建正确的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52124921/

相关文章:

google-app-engine - 为什么 "go test -v"没有看到 GOPATH 或 GOPATH 但 "go env"有?

Django (JSONField) 和 tastypie

json - 仅当 AWS ECS 集群不存在时,如何通过 AWS Cloudformation 创建它

javascript - 使用 Node.js 连接和聚合 json 对象数据

go - 重复查找大文件并写入会影响写入速度吗?

go - Prometheus 添加自定义指标

java - 使用数据文件进行 Junit 测试

Java - JSONObject 仅解析 1 个字符串?

go - 缓冲 channel 是否维持秩序?

Golang ...字符串类型参数函数