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.

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Amit Kumar Gupta

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.