forked from mholt/json-to-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json-to-go.js
244 lines (216 loc) · 5.28 KB
/
json-to-go.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/*
JSON-to-Go
by Matt Holt
https://github.com/mholt/json-to-go
A simple utility to translate JSON into a Go type definition.
*/
function jsonToGo(json, typename)
{
var data;
var scope;
var go = "";
var tabs = 0;
try
{
data = JSON.parse(json.replace(/\.0/g, ".1")); // hack that forces floats to stay as floats
scope = data;
}
catch (e)
{
return {
go: "",
error: e.message
};
}
typename = format(typename || "AutoGenerated");
append("type "+typename+" ");
parseScope(scope);
return { go: go };
function parseScope(scope)
{
if (typeof scope === "object" && scope !== null)
{
if (Array.isArray(scope))
{
var sliceType, scopeLength = scope.length;
for (var i = 0; i < scopeLength; i++)
{
var thisType = goType(scope[i]);
if (!sliceType)
sliceType = thisType;
else if (sliceType != thisType)
{
sliceType = mostSpecificPossibleGoType(thisType, sliceType);
if (sliceType == "interface{}")
break;
}
}
append("[]");
if (sliceType == "struct") {
var allFields = {};
// for each field counts how many times appears
for (var i = 0; i < scopeLength; i++)
{
var keys = Object.keys(scope[i])
for (var k in keys)
{
var keyname = keys[k];
if (!(keyname in allFields)) {
allFields[keyname] = {
value: scope[i][keyname],
count: 0
}
}
allFields[keyname].count++;
}
}
// create a common struct with all fields found in the current array
// omitempty dict indicates if a field is optional
var keys = Object.keys(allFields), struct = {}, omitempty = {};
for (var k in keys)
{
var keyname = keys[k], elem = allFields[keyname];
struct[keyname] = elem.value;
omitempty[keyname] = elem.count != scopeLength;
}
parseStruct(struct, omitempty); // finally parse the struct !!
}
else if (sliceType == "slice") {
parseScope(scope[0])
}
else
append(sliceType || "interface{}");
}
else
{
parseStruct(scope);
}
}
else
append(goType(scope));
}
function parseStruct(scope, omitempty)
{
append("struct {\n");
++tabs;
var keys = Object.keys(scope);
for (var i in keys)
{
var keyname = keys[i];
indent(tabs);
append(format(keyname)+" ");
parseScope(scope[keyname]);
append(' `json:"'+keyname);
if (omitempty && omitempty[keyname] === true)
{
append(',omitempty');
}
append('"`\n');
}
indent(--tabs);
append("}");
}
function indent(tabs)
{
for (var i = 0; i < tabs; i++)
go += '\t';
}
function append(str)
{
go += str;
}
// Sanitizes and formats a string to make an appropriate identifier in Go
function format(str)
{
if (!str)
return "";
else if (str.match(/^\d+$/))
str = "Num" + str;
else if (str.charAt(0).match(/\d/))
{
var numbers = {'0': "Zero_", '1': "One_", '2': "Two_", '3': "Three_",
'4': "Four_", '5': "Five_", '6': "Six_", '7': "Seven_",
'8': "Eight_", '9': "Nine_"};
str = numbers[str.charAt(0)] + str.substr(1);
}
return toProperCase(str).replace(/[^a-z0-9]/ig, "") || "NAMING_FAILED";
}
// Determines the most appropriate Go type
function goType(val)
{
if (val === null)
return "interface{}";
switch (typeof val)
{
case "string":
if (/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)/.test(val))
return "time.Time";
else
return "string";
case "number":
if (val % 1 === 0)
{
if (val > -2147483648 && val < 2147483647)
return "int";
else
return "int64";
}
else
return "float64";
case "boolean":
return "bool";
case "object":
if (Array.isArray(val))
return "slice";
return "struct";
default:
return "interface{}";
}
}
// Given two types, returns the more specific of the two
function mostSpecificPossibleGoType(typ1, typ2)
{
if (typ1.substr(0, 5) == "float"
&& typ2.substr(0, 3) == "int")
return typ1;
else if (typ1.substr(0, 3) == "int"
&& typ2.substr(0, 5) == "float")
return typ1;
else
return "interface{}";
}
// Proper cases a string according to Go conventions
function toProperCase(str)
{
// https://github.com/golang/lint/blob/39d15d55e9777df34cdffde4f406ab27fd2e60c0/lint.go#L695-L731
var commonInitialisms = [
"API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP",
"HTTPS", "ID", "IP", "JSON", "LHS", "QPS", "RAM", "RHS", "RPC", "SLA",
"SMTP", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "UID", "UUID", "URI",
"URL", "UTF8", "VM", "XML", "XSRF", "XSS"
];
return str.replace(/(^|[^a-zA-Z])([a-z]+)/g, function(unused, sep, frag)
{
if (commonInitialisms.indexOf(frag.toUpperCase()) >= 0)
return sep + frag.toUpperCase();
else
return sep + frag[0].toUpperCase() + frag.substr(1).toLowerCase();
}).replace(/([A-Z])([a-z]+)/g, function(unused, sep, frag)
{
if (commonInitialisms.indexOf(sep + frag.toUpperCase()) >= 0)
return (sep + frag).toUpperCase();
else
return sep + frag;
});
}
}
if (typeof module != 'undefined') {
if (!module.parent) {
process.stdin.on('data', function(buf) {
var json = buf.toString('utf8')
console.log(jsonToGo(json).go)
})
} else {
module.exports = jsonToGo
}
}