json-to-go icon indicating copy to clipboard operation
json-to-go copied to clipboard

Error on generation of nested objects in array

Open decima opened this issue 5 years ago • 3 comments

Found a little issue on substructures in nested objects in array.

For example :

[
  {
    "a": 1,
    "b": {
	"b1": 1,
	"b2": "B2"
    }
  },
  {
    "b": {
  	"b3": 3,
        "b4": "B4"
    }
  }
]

will generate:

type AutoGenerated []struct {
	A int `json:"a,omitempty"`
	B struct {
		B1 int    `json:"b1"`
		B2 string `json:"b2"`
	} `json:"b,omitempty"`
	B struct {
		B3 int    `json:"b3"`
		B4 string `json:"b4"`
	} `json:"b,omitempty"`
}

decima avatar Aug 26 '20 13:08 decima

Thanks!

Does anyone have time to submit a patch? I'm a bit swamped this week and next.

mholt avatar Aug 26 '20 16:08 mholt

I take a look at the code, and I don't know which "merge/duplicate"strategy you want to use :

should B be a struct with B1,B2,B3,B4 or should we have two structures BFirst {B1, B2} BSecond {B3,B4} ?

The second strategy (name it "duplicate") seems easier to implement as we could image B struct and B_uuidv4() struct as you already do. For my case I wanted the first strategy ("merge") but that would mean a deep merge. This would end up with weird behaviour if we have nested array in the nested objects.

In my case I was on a structure like this:

{
	"stores": [{
			"sign": "wallmart",
			"address": {
				"street": "1st street",
				"zipcode": "123456",
				"city": "randomCity1",
				"phone": "1234567890"
			}
		},
		{
			"sign": "bestbuy",
			"address": {
				"street": "2nd street",
				"zipcode": "654321",
				"city": "randomCity2"
			}
		}
	]
}

and it seems pretty obvious that in this case, addresses structs should be merged. In other less well-structured jsons, we would like to end up with two structures

So basically in which direction would you like to go?

decima avatar Aug 27 '20 07:08 decima

Similar issue with key-value in json. Ex:

    "packages":[
        {
            "name":"p1",
            "version":""
        }
    ],
    "vendorPackages":{
        "vp1":{
            "name":"",
            "version":"123"
        },
        "vp2":{
            "name":"456",
            "version":""
        }
    }
}

Should be

type Packages struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

type GMF struct {
	Packages       []Packages          `json:"packages"`
	VendorPackages map[string]Packages `json:"vendorPackages"`
}

Instead of

type Autogenerated struct {
	Packages []struct {
		Name    string `json:"name"`
		Version string `json:"version"`
	} `json:"packages"`
	Vendorpackages struct {
		Vp1 struct {
			Name    string `json:"name"`
			Version string `json:"version"`
		} `json:"vp1"`
		Vp2 struct {
			Name    string `json:"name"`
			Version string `json:"version"`
		} `json:"vp2"`
	} `json:"vendorPackages"`
}

chatenilesh avatar Mar 23 '21 09:03 chatenilesh