diff --git a/json-to-go.js b/json-to-go.js index e1c1515..b9a4fa2 100644 --- a/json-to-go.js +++ b/json-to-go.js @@ -156,6 +156,14 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty continue; } + // if both one of the two objects is empty assume they are identical + if (currentKeys.length == 0 && existingKeys.length > 0 || + currentKeys.length > 0 && existingKeys.length == 0) { + allFields[keyname].count++; + insideOmitEmpty = true // as the whole object is empty, all nested elements are omitempty + continue; + } + const comparisonResult = compareObjectKeys( Object.keys(currentValue), Object.keys(existingValue) diff --git a/json-to-go.test.js b/json-to-go.test.js index 809c088..56700dc 100644 --- a/json-to-go.test.js +++ b/json-to-go.test.js @@ -164,6 +164,7 @@ function testFiles() { "double-nested-objects", "array-with-nonmatching-types", "array-with-mergable-objects", + "array-with-mergable-empty-object", ]; for (const testCase of testCases) { diff --git a/tests/array-with-mergable-empty-object.go b/tests/array-with-mergable-empty-object.go new file mode 100644 index 0000000..f63b01e --- /dev/null +++ b/tests/array-with-mergable-empty-object.go @@ -0,0 +1,14 @@ +type AutoGenerated struct { + Booleanfield bool `json:"booleanfield"` + Somearray []Somearray `json:"somearray"` + Date string `json:"date"` +} +type Features struct { + Age int `json:"age,omitempty"` + Height int `json:"height,omitempty"` +} +type Somearray struct { + ID int `json:"id"` + Name string `json:"name"` + Features Features `json:"features"` +} diff --git a/tests/array-with-mergable-empty-object.json b/tests/array-with-mergable-empty-object.json new file mode 100644 index 0000000..2b895d6 --- /dev/null +++ b/tests/array-with-mergable-empty-object.json @@ -0,0 +1,19 @@ +{ + "booleanfield": true, + "somearray": [ + { + "id": 1, + "name": "John Doe", + "features": { + "age": 49, + "height": 175 + } + }, + { + "id": 3, + "name": "John Doe", + "features": {} + } + ], + "date": "2024-07-24" +}