dongshi2458 2019-09-02 23:44
浏览 325
已采纳

如何在Golang中使用嵌套的递归数据编写结构

I have data like following

{
    "cars": {
        "toyota": [
            "sedan",
            "pickup"
        ],
        "honda": [
            "sedan",
            "couple",
            "pickup"
        ]
                ....
    }
}

The list might continue grow. I am trying to find out a proper struct to server the data and return to A http responsewriter.

the struct that I had.

type Autos struct {
    Cars struct {
        Toyota []string `json:"toyota"`
        Honda  []string `json:"honda"`
    } `json:"cars"`
}

But the above struct has predefined "Toyota" "Honda"

I am looking for a way to only use one or two struct to represent the data structure. Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongza6247 2019-09-03 00:12
    关注

    You can do:

    type Autos struct {
        Cars map[string][]string `json:"cars"`
    }
    

    Here's a full working example, that prints "coupe":

    package main
    
    import (
        "encoding/json"
    )
    
    type Autos struct {
        Cars map[string][]string `json:"cars"`
    }
    
    func main() {
        x := `{
        "cars": {
            "toyota": [
                "sedan",
                "pickup"
            ],
            "honda": [
                "sedan",
                "coupe",
                "pickup"
            ]
        }
    }`
    
        var a Autos
        err := json.Unmarshal([]byte(x), &a)
        if err != nil {
            panic(err)
        }
        println(a.Cars["honda"][1])
    }
    

    Playground link

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型