Skip to content

Commit 16d1c31

Browse files
committed
Bug fix for appropriate Go identifier names
1 parent 6dde3ea commit 16d1c31

File tree

2 files changed

+12
-6
lines changed

2 files changed

+12
-6
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,6 @@ Contributions are welcome! Open a pull request to fix a bug, or open an issue to
1212

1313
### Credits
1414

15-
JSON-to-Go is brought to you by Matt Holt.
15+
JSON-to-Go is brought to you by Matt Holt ([mholt6](https://twitter.com/mholt6)).
1616

1717
The Go Gopher is originally by Renee French. This artwork is an adaptation.

json-to-go.js

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ function jsonToGo(json, typename)
2727
};
2828
}
2929

30-
typename = format(typename || "GIVE_ME_A_NAME");
30+
typename = format(typename || "AutoGenerated");
3131
append("type "+typename+" ");
3232

3333
parseScope(scope);
@@ -93,20 +93,24 @@ function jsonToGo(json, typename)
9393
go += str;
9494
}
9595

96+
// Sanitizes and formats a string to make an appropriate identifier in Go
9697
function format(str)
9798
{
98-
if (str.match(/^\d+$/))
99-
str = "Number" + str;
99+
if (!str)
100+
return "";
101+
else if (str.match(/^\d+$/))
102+
str = "Num" + str;
100103
else if (str.charAt(0).match(/\d/))
101104
{
102105
var numbers = {'0': "Zero_", '1': "One_", '2': "Two_", '3': "Three_",
103106
'4': "Four_", '5': "Five_", '6': "Six_", '7': "Seven_",
104107
'8': "Eight_", '9': "Nine_"};
105108
str = numbers[str.charAt(0)] + str.substr(1);
106109
}
107-
return toProperCase(str).replace(/\s|_|-/g, "");
110+
return toProperCase(str).replace(/[^a-z0-9]/ig, "");
108111
}
109112

113+
// Determines the most appropriate Go type
110114
function goType(val)
111115
{
112116
if (val === null)
@@ -140,6 +144,7 @@ function jsonToGo(json, typename)
140144
}
141145
}
142146

147+
// Given two types, returns the more specific of the two
143148
function mostSpecificPossibleGoType(typ1, typ2)
144149
{
145150
if (typ1.substr(0, 5) == "float"
@@ -152,6 +157,7 @@ function jsonToGo(json, typename)
152157
return "interface{}";
153158
}
154159

160+
// Proper cases a string according to Go conventions
155161
function toProperCase(str)
156162
{
157163
// https://github.com/golang/lint/blob/39d15d55e9777df34cdffde4f406ab27fd2e60c0/lint.go#L695-L731
@@ -162,7 +168,7 @@ function jsonToGo(json, typename)
162168
"URL", "UTF8", "VM", "XML", "XSRF", "XSS"
163169
];
164170

165-
return str.replace(/(^|[\s_-])([a-z]+)/g, function(unused, sep, frag)
171+
return str.replace(/(^|[^a-z])([a-z]+)/ig, function(unused, sep, frag)
166172
{
167173
if (commonInitialisms.indexOf(frag.toUpperCase()) >= 0)
168174
return sep + frag.toUpperCase();

0 commit comments

Comments
 (0)