Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions generator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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: "" +
Expand Down
25 changes: 24 additions & 1 deletion value.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ import (
"fmt"
"maps"
"slices"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"

"github.com/fatih/structtag"
)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
}