Skip to content

Commit 2a1a27b

Browse files
committed
support merged top-level objects inside arrays
1 parent 25237b6 commit 2a1a27b

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

json-to-go.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
8282
appender(slice);
8383
else
8484
append(slice)
85+
86+
// TODO: structs need a proper recursive solution to fix omitempty and nesting
8587
if (sliceType == "struct") {
8688
const allFields = {};
8789

@@ -103,6 +105,28 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
103105
const currentValue = scope[i][keyname];
104106

105107
if (compareObjects(existingValue, currentValue)) {
108+
const currentKeys = Object.keys(currentValue)
109+
const existingKeys = Object.keys(existingValue)
110+
111+
// try to merge two object fields instead of creating separate ones
112+
if (typeof existingValue === "object"
113+
&& existingKeys.length > 0
114+
&& typeof currentValue === "object"
115+
&& currentKeys.length > 0
116+
) {
117+
var mergedValues = existingValue
118+
for (const key of currentKeys) {
119+
if (!Object.keys(mergedValues).includes(key)) {
120+
mergedValues[key] = currentValue[key]
121+
// TODO: find a proper handling of omitempty for nested structs
122+
allOmitempty = true
123+
}
124+
}
125+
allFields[keyname].value = mergedValues;
126+
allFields[keyname].count++;
127+
continue;
128+
}
129+
106130
const comparisonResult = compareObjectKeys(
107131
Object.keys(currentValue),
108132
Object.keys(existingValue)

0 commit comments

Comments
 (0)