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 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探