Skip to content

Commit a2f7c51

Browse files
committed
make non-matching types in arrays type "any"
1 parent 1e827f8 commit a2f7c51

4 files changed

+52
-2
lines changed

json-to-go.js

+18-2
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,16 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
102102
const existingValue = allFields[keyname].value;
103103
const currentValue = scope[i][keyname];
104104

105-
if (compareObjects(existingValue, currentValue)) {
105+
if (!areSameType(existingValue, currentValue)) {
106+
if(existingValue !== null) {
107+
allFields[keyname].value = null // force type "any" if types are not identical
108+
console.warn(`Warning: key "${keyname}" uses multiple types. Defaulting to type "any".`)
109+
}
110+
allFields[keyname].count++
111+
continue
112+
}
113+
114+
if (areObjects(existingValue, currentValue)) {
106115
const comparisonResult = compareObjectKeys(
107116
Object.keys(currentValue),
108117
Object.keys(existingValue)
@@ -444,12 +453,19 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
444453
return unique
445454
}
446455

447-
function compareObjects(objectA, objectB) {
456+
function areObjects(objectA, objectB) {
448457
const object = "[object Object]";
449458
return Object.prototype.toString.call(objectA) === object
450459
&& Object.prototype.toString.call(objectB) === object;
451460
}
452461

462+
function areSameType(objectA, objectB) {
463+
// prototype.toString required to compare Arrays and Objects
464+
const typeA = Object.prototype.toString.call(objectA)
465+
const typeB = Object.prototype.toString.call(objectB)
466+
return typeA === typeB
467+
}
468+
453469
function compareObjectKeys(itemAKeys, itemBKeys) {
454470
const lengthA = itemAKeys.length;
455471
const lengthB = itemBKeys.length;

json-to-go.test.js

+1
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ function testFiles() {
162162
const testCases = [
163163
"duplicate-top-level-structs",
164164
"double-nested-objects",
165+
"array-with-nonmatching-types",
165166
];
166167

167168
for (const testCase of testCases) {

tests/array-with-nonmatching-types.go

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
type AutoGenerated struct {
2+
Booleanfield bool `json:"booleanfield"`
3+
Somearray []Somearray `json:"somearray"`
4+
Date string `json:"date"`
5+
}
6+
type Somearray struct {
7+
ID any `json:"id"`
8+
Name string `json:"name"`
9+
Features any `json:"features"`
10+
}
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
{
2+
"booleanfield": true,
3+
"somearray": [
4+
{
5+
"id": 1,
6+
"name": "John Doe",
7+
"features": {
8+
"age": 49,
9+
"height": 175
10+
}
11+
},
12+
{
13+
"id": "2",
14+
"name": "John Doe",
15+
"features": [
16+
"2",
17+
"3",
18+
"4"
19+
]
20+
}
21+
],
22+
"date": "2024-07-24"
23+
}

0 commit comments

Comments
 (0)