DudiDude
DudiDude

Reputation: 413

Unmarshal a dynamic json

I have a bunch of JSON files that I need to Unmarshal. They have basically the same format, but different "length"

one example https://pastebin.com/htt6k658

another example https://pastebin.com/NR1Z08f4

I have tried several methods, like building structs like

type TagType struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
    Slug string `json:"slug"`
    tags []Tag  `json:"tags"`
}

type Tag struct {
    ID   int    `json:"users"`
    Name string `json:"name"`
    Slug string `json:"slug"`
}

also with an interface, like json.Unmarshal([]byte(empJson), &result)

but none of these methods worked.

Upvotes: 0

Views: 44

Answers (2)

Twistleton
Twistleton

Reputation: 2935

You can use a online tool like https://transform.tools/json-to-go for generating the Go struct:

  type AutoGenerated []struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
    Slug string `json:"slug"`
    Tags []struct {
        ID   int    `json:"id"`
        Name string `json:"name"`
        Slug string `json:"slug"`
        } `json:"tags"`
    }

Upvotes: 0

Burak Serdar
Burak Serdar

Reputation: 51567

The JSON input is an array, so this should work:

var result []TagType
json.Unmarshal(data,&result)

Upvotes: 1

Related Questions