Skip to content

Commit 08f2078

Browse files
committed
fix duplicate top-level structs
1 parent e7be945 commit 08f2078

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

json-to-go.js

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
1919
let accumulator = "";
2020
let innerTabs = 0;
2121
let parent = "";
22+
let globallySeenTypeNames = [];
2223

2324
try
2425
{
@@ -197,8 +198,15 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
197198
{
198199
const keyname = getOriginalName(keys[i]);
199200
indenter(innerTabs)
200-
const typename = uniqueTypeName(format(keyname), seenTypeNames)
201-
seenTypeNames.push(typename)
201+
let typename
202+
// structs will be defined on the top level of the go file, so they need to be globally unique
203+
if (typeof scope[keys[i]] === "object" && scope[keys[i]] !== null) {
204+
typename = uniqueTypeName(format(keyname), globallySeenTypeNames, parent)
205+
globallySeenTypeNames.push(typename)
206+
} else {
207+
typename = uniqueTypeName(format(keyname), seenTypeNames)
208+
seenTypeNames.push(typename)
209+
}
202210

203211
appender(typename+" ");
204212
parent = typename
@@ -222,8 +230,16 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
222230
{
223231
const keyname = getOriginalName(keys[i]);
224232
indent(tabs);
225-
const typename = uniqueTypeName(format(keyname), seenTypeNames)
226-
seenTypeNames.push(typename)
233+
let typename
234+
// structs will be defined on the top level of the go file, so they need to be globally unique
235+
if (typeof scope[keys[i]] === "object" && scope[keys[i]] !== null) {
236+
typename = uniqueTypeName(format(keyname), globallySeenTypeNames, parent)
237+
globallySeenTypeNames.push(typename)
238+
} else {
239+
typename = uniqueTypeName(format(keyname), seenTypeNames)
240+
seenTypeNames.push(typename)
241+
}
242+
227243
append(typename+" ");
228244
parent = typename
229245
parseScope(scope[keys[i]], depth);
@@ -269,11 +285,19 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
269285

270286
// Generate a unique name to avoid duplicate struct field names.
271287
// This function appends a number at the end of the field name.
272-
function uniqueTypeName(name, seen) {
288+
function uniqueTypeName(name, seen, prefix=null) {
273289
if (seen.indexOf(name) === -1) {
274290
return name;
275291
}
276292

293+
// check if we can get a unique name by prefixing it
294+
if(prefix) {
295+
name = prefix+name
296+
if (seen.indexOf(name) === -1) {
297+
return name;
298+
}
299+
}
300+
277301
let i = 0;
278302
while (true) {
279303
let newName = name + i.toString();

0 commit comments

Comments
 (0)