From 86dc28bd9305a36e0daf7fc2d9cc064d5287b877 Mon Sep 17 00:00:00 2001 From: Jay Hemnani <193022578+jayhemnani9910@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:42:14 +0530 Subject: [PATCH] fix: give fields with the same exported name unique names --- generator_test.go | 14 ++++++++++++++ value.go | 25 ++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/generator_test.go b/generator_test.go index 534ee4f..1b897d1 100644 --- a/generator_test.go +++ b/generator_test.go @@ -995,6 +995,20 @@ func TestObserveJSONGoCode(t *testing.T) { "\n" + "type T any\n", }, + { + name: "duplicate_field_names", + json: "" + + `{"+1":1,"-1":2,"id":3,"ID":4}`, + expectedGoCodeStr: "" + + "package main\n" + + "\n" + + "type T struct {\n" + + "\t_1 int `json:\"+1\"`\n" + + "\t_1_2 int `json:\"-1\"`\n" + + "\tID int `json:\"ID\"`\n" + + "\tID2 int `json:\"id\"`\n" + + "}\n", + }, { name: "bool", json: "" + diff --git a/value.go b/value.go index 06faf0f..cbc1acc 100644 --- a/value.go +++ b/value.go @@ -6,8 +6,11 @@ import ( "fmt" "maps" "slices" + "strconv" "strings" "time" + "unicode" + "unicode/utf8" "github.com/fatih/structtag" ) @@ -277,6 +280,7 @@ func (v *value) goType(observations int, options *generateOptions) goType { b := &bytes.Buffer{} fmt.Fprintf(b, "struct {\n") var unparsableProperties []string + fieldNames := make(map[string]struct{}) for _, property := range slices.Sorted(maps.Keys(v.objectProperties)) { if isUnparsableProperty(property) { unparsableProperties = append(unparsableProperties, property) @@ -322,7 +326,7 @@ func (v *value) goType(observations int, options *generateOptions) goType { _ = tags.Set(tag) } - fmt.Fprintf(b, "%s %s `%s`\n", options.exportNameFunc(property), goType.typeStr, tags) + fmt.Fprintf(b, "%s %s `%s`\n", uniqueFieldName(options.exportNameFunc(property), fieldNames), goType.typeStr, tags) } for _, property := range unparsableProperties { fmt.Fprintf(b, "// %q cannot be unmarshalled into a struct field by encoding/json.\n", property) @@ -403,3 +407,22 @@ func (v *value) goType(observations int, options *generateOptions) goType { } } } + +// uniqueFieldName returns name, or name with a numeric suffix if another field +// of the same struct already uses it (e.g. JSON keys "+1" and "-1", or "id" and +// "ID"). +func uniqueFieldName(name string, fieldNames map[string]struct{}) string { + separator := "" + if r, _ := utf8.DecodeLastRuneInString(name); unicode.IsDigit(r) { + separator = "_" + } + unique := name + for i := 2; ; i++ { + if _, ok := fieldNames[unique]; !ok { + break + } + unique = name + separator + strconv.Itoa(i) + } + fieldNames[unique] = struct{}{} + return unique +}