mholt / json-to-go

Translates JSON into a Go type in your browser instantly (original)
https://mholt.github.io/json-to-go/
MIT License
4.51k stars 475 forks source link

Objects of varying structure within a list not added to struct #6

Closed arussellsaw closed 8 years ago

arussellsaw commented 9 years ago

The input string:

{
    "native": {
        "ver": 1,
        "link": {
            "url": "deeplink://deeplink/url/into/app",
            "fallback": "http: //i.am.a/URL",
            "clicktrackers": [
                "http: //a.com/a",
                "http: //b.com/b"
            ]
        },
        "imptrackers": [
            "http: //a.com/a",
            "http: //b.com/b"
        ],
        "assets": [
            {
                "id": 1,
                "title": {
                    "text": "InstallBOA"
                },
                "link": {
                    "url": "http: //i.am.a/URL"
                }
            },
            {
                "id": 2,
                "data": {
                    "value": 5
                }
            },
            {
                "id": 3,
                "img": {
                    "url": "http: //cdn.mobad.com/ad.png",
                    "w": 64,
                    "h": 64
                }
            },
            {
                "id": 4,
                "data": {
                    "value": "Install"
                },
                "link": {
                    "url": "http: //i.am.a/URL"
                }
            }
        ]
    }
}

returns the Go Struct :

type Autogenerated struct {

    Native struct {

        Ver int `json:"ver"`

        Link struct {

            URL string `json:"url"`

            Fallback string `json:"fallback"`

            Clicktrackers []string `json:"clicktrackers"`

        } `json:"link"`

        Imptrackers []string `json:"imptrackers"`

        Assets []struct {

            ID int `json:"id"`

            Title struct {

                Text string `json:"text"`

            } `json:"title"`

            Link struct {

                URL string `json:"url"`

            } `json:"link"`

        } `json:"assets"`

    } `json:"native"`

}

the "img" object is missing from the assets struct. i appreciate that this JSON is kinda ugly, but still a bug!

mholt commented 9 years ago

You caught me: I was lazy and only evaluated the first element in an array to determine its structure.

I'll look into this soon, thanks for the report!

ghost commented 9 years ago

Much smaller example:

[
    {
        "Occupation":"carpenter"
    },
    {
        "Name":"bill",
        "Occupation":"woodcutter"
    }
]

gives:

type Autogenerated []struct {
    Occupation string `json:"Occupation"`
}
yanpozka commented 8 years ago

Hi @mholt thanks for this repo and idea, I like a lot. I just created a PR who solves this issue