如何为json创建正确的结构

问题描述 投票:-1回答:1

如何正确解析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"`
}

但我不知道如何解析像“你好”和“世界”这样的包装

json go
1个回答
1
投票

您只需要构建根映射。

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

这里的helloworld也在地图内。所以你也需要构建它们。

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

游乐场示例:https://play.golang.org/p/VZ9Bn215dDW

© www.soinside.com 2019 - 2024. All rights reserved.