How to write a struct with nested recursive data in golang

347 views Asked by At

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

There are 1 answers

1
Amit Kumar Gupta On BEST ANSWER

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