Skip to content

Commit 4b17b38

Browse files
committed
support merged top-level objects inside arrays
1 parent 086b5b2 commit 4b17b38

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
@@ -75,6 +75,8 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
7575
appender(slice);
7676
else
7777
append(slice)
78+
79+
// TODO: structs need a proper recursive solution to fix omitempty and nesting
7880
if (sliceType == "struct") {
7981
const allFields = {};
8082

@@ -96,6 +98,28 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
9698
const currentValue = scope[i][keyname];
9799

98100
if (compareObjects(existingValue, currentValue)) {
101+
const currentKeys = Object.keys(currentValue)
102+
const existingKeys = Object.keys(existingValue)
103+
104+
// try to merge two object fields instead of creating separate ones
105+
if (typeof existingValue === "object"
106+
&& existingKeys.length > 0
107+
&& typeof currentValue === "object"
108+
&& currentKeys.length > 0
109+
) {
110+
var mergedValues = existingValue
111+
for (const key of currentKeys) {
112+
if (!Object.keys(mergedValues).includes(key)) {
113+
mergedValues[key] = currentValue[key]
114+
// TODO: find a proper handling of omitempty for nested structs
115+
allOmitempty = true
116+
}
117+
}
118+
allFields[keyname].value = mergedValues;
119+
allFields[keyname].count++;
120+
continue;
121+
}
122+
99123
const comparisonResult = compareObjectKeys(
100124
Object.keys(currentValue),
101125
Object.keys(existingValue)

0 commit comments

Comments
 (0)