Home > Mobile >  Unmarshal a dynamic json
Unmarshal a dynamic json

Time:12-06

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.

CodePudding user response:

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

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

CodePudding user response:

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"`
    }
  • Related