diff --git a/json-to-go.js b/json-to-go.js index cf4c509..120486f 100644 --- a/json-to-go.js +++ b/json-to-go.js @@ -102,7 +102,16 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty const existingValue = allFields[keyname].value; const currentValue = scope[i][keyname]; - if (compareObjects(existingValue, currentValue)) { + if (!areSameType(existingValue, currentValue)) { + if(existingValue !== null) { + allFields[keyname].value = null // force type "any" if types are not identical + console.warn(`Warning: key "${keyname}" uses multiple types. Defaulting to type "any".`) + } + allFields[keyname].count++ + continue + } + + if (areObjects(existingValue, currentValue)) { const comparisonResult = compareObjectKeys( Object.keys(currentValue), Object.keys(existingValue) @@ -444,12 +453,19 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty return unique } - function compareObjects(objectA, objectB) { + function areObjects(objectA, objectB) { const object = "[object Object]"; return Object.prototype.toString.call(objectA) === object && Object.prototype.toString.call(objectB) === object; } + function areSameType(objectA, objectB) { + // prototype.toString required to compare Arrays and Objects + const typeA = Object.prototype.toString.call(objectA) + const typeB = Object.prototype.toString.call(objectB) + return typeA === typeB + } + function compareObjectKeys(itemAKeys, itemBKeys) { const lengthA = itemAKeys.length; const lengthB = itemBKeys.length; diff --git a/json-to-go.test.js b/json-to-go.test.js index 66cbe55..c2a6e3f 100644 --- a/json-to-go.test.js +++ b/json-to-go.test.js @@ -162,6 +162,7 @@ function testFiles() { const testCases = [ "duplicate-top-level-structs", "double-nested-objects", + "array-with-nonmatching-types", ]; for (const testCase of testCases) { diff --git a/tests/array-with-nonmatching-types.go b/tests/array-with-nonmatching-types.go new file mode 100644 index 0000000..967a551 --- /dev/null +++ b/tests/array-with-nonmatching-types.go @@ -0,0 +1,10 @@ +type AutoGenerated struct { + Booleanfield bool `json:"booleanfield"` + Somearray []Somearray `json:"somearray"` + Date string `json:"date"` +} +type Somearray struct { + ID any `json:"id"` + Name string `json:"name"` + Features any `json:"features"` +} diff --git a/tests/array-with-nonmatching-types.json b/tests/array-with-nonmatching-types.json new file mode 100644 index 0000000..7a7ed38 --- /dev/null +++ b/tests/array-with-nonmatching-types.json @@ -0,0 +1,23 @@ +{ + "booleanfield": true, + "somearray": [ + { + "id": 1, + "name": "John Doe", + "features": { + "age": 49, + "height": 175 + } + }, + { + "id": "2", + "name": "John Doe", + "features": [ + "2", + "3", + "4" + ] + } + ], + "date": "2024-07-24" +}