0

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.

wzcwts521
  • 15
  • 4
  • 1
    Possible duplicate of [How Do I Unmarshal Dynamic Viper or JSON keys as part of struct field in go](https://stackoverflow.com/questions/50749869/), [golang struct for json with arbitrary keys](https://stackoverflow.com/questions/15817720/), ... – Charlie Tumahai Sep 03 '19 at 00:13

1 Answers1

0

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

Amit Kumar Gupta
  • 17,184
  • 7
  • 46
  • 64