-
Notifications
You must be signed in to change notification settings - Fork 8
/
relaxed-json.js
635 lines (550 loc) · 17.6 KB
/
relaxed-json.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
/*
Copyright (c) 2013, Oleg Grenrus
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Oleg Grenrus nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL OLEG GRENRUS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function () {
"use strict";
/*
slightly different from ES5 some, without cast to boolean
[x, y, z].some(f):
ES5: !! ( f(x) || f(y) || f(z) || false)
this: ( f(x) || f(y) || f(z) || false)
*/
// :: array -> fn -> *
function some(array, f) {
var acc = false;
for (var i = 0; i < array.length; i++) {
acc = f(array[i], i, array);
if (acc) {
return acc;
}
}
return acc;
}
// typify: type tokenSpec = { re: regexp, f : fn }
// typify: type tokenType = "atom" | "number" | "string" | "[" | "]" | "{" | "}" | ":" | "," | " " | "eof"
// typify: type rawToken = { type: tokenType, match: string, value: any }
// typify: type token = rawToken & { line: nat }
// typify: type parseToken = { type: tokenType, value: any, line: nat }
// :: array tokenSpec -> fn
function makeLexer(tokenSpecs) {
// :: string -> array token
return function (contents) {
var tokens = [];
var line = 1;
// :: -> { raw: string, matched: * } | null
function findToken() {
return some(tokenSpecs, function (tokenSpec) {
var m = tokenSpec.re.exec(contents);
if (m) {
var raw = m[0];
contents = contents.slice(raw.length);
return {
raw: raw,
matched: tokenSpec.f(m),
};
} else {
return undefined;
}
});
}
while (contents !== "") {
var matched = findToken();
if (!matched) {
var err = new SyntaxError("Unexpected character: " + contents[0] + "; input: " + contents.substr(0, 100));
err.line = line;
throw err;
}
// add line to token
matched.matched.line = line;
// count lines
line += matched.raw.replace(/[^\n]/g, "").length;
tokens.push(matched.matched);
}
return tokens;
};
}
// :: tuple string string -> rawToken
function fStringSingle(m) {
// String in single quotes
var content = m[1].replace(/([^'\\]|\\['bnrtf\\]|\\u[0-9a-fA-F]{4})/g, function (mm) {
if (mm === "\"") {
return "\\\"";
} else if (mm === "\\'") {
return "'";
} else {
return mm;
}
});
return {
type: "string",
match: "\"" + content + "\"",
value: JSON.parse("\"" + content + "\""), // abusing real JSON.parse to unquote string
};
}
// :: tuple string -> rawToken
function fStringDouble(m) {
return {
type: "string",
match: m[0],
value: JSON.parse(m[0]),
};
}
// :: tuple string -> rawToken
function fIdentifier(m) {
// identifiers are transformed into strings
return {
type: "string",
value: m[0],
match: "\"" + m[0].replace(/./g, function (c) {
return c === "\\" ? "\\\\" : c;
}) + "\"",
};
}
// :: tuple string -> rawToken
function fComment(m) {
// comments are whitespace, leave only linefeeds
return {
type: " ",
match: m[0].replace(/./g, function (c) {
return (/\s/).test(c) ? c : " ";
}),
};
}
// :: tuple string -> rawToken
function fNumber(m) {
return {
type: "number",
match: m[0],
value: parseFloat(m[0]),
};
}
// :: tuple ("null" | "true" | "false") -> rawToken
function fKeyword(m) {
var value;
switch (m[0]) {
case "null": value = null; break;
case "true": value = true; break;
case "false": value = false; break;
// no default
}
return {
type: "atom",
match: m[0],
value: value,
};
}
// :: boolean -> array tokenSpec
function makeTokenSpecs(relaxed) {
// :: string -> fn
function f(type) {
// :: tuple string -> rawToken
return function (m) {
return { type: type, match: m[0] };
};
}
var ret = [
{ re: /^\s+/, f: f(" ") },
{ re: /^\{/, f: f("{") },
{ re: /^\}/, f: f("}") },
{ re: /^\[/, f: f("[") },
{ re: /^\]/, f: f("]") },
{ re: /^,/, f: f(",") },
{ re: /^:/, f: f(":") },
{ re: /^(?:true|false|null)/, f: fKeyword },
{ re: /^\-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/, f: fNumber },
{ re: /^"(?:[^"\\]|\\["bnrtf\\\/]|\\u[0-9a-fA-F]{4})*"/, f: fStringDouble },
];
// additional stuff
if (relaxed) {
ret = ret.concat([
{ re: /^'((?:[^'\\]|\\['bnrtf\\\/]|\\u[0-9a-fA-F]{4})*)'/, f: fStringSingle },
{ re: /^\/\/.*?(?:\r\n|\r|\n)/, f: fComment },
{ re: /^\/\*[\s\S]*?\*\//, f: fComment },
{ re: /^[$a-zA-Z0-9_\-+\.\*\?!\|&%\^\/#\\]+/, f: fIdentifier },
]);
}
return ret;
}
var lexer = makeLexer(makeTokenSpecs(true));
var strictLexer = makeLexer(makeTokenSpecs(false));
// :: array token -> nat -> nat?
function previousNWSToken(tokens, index) {
for (; index >= 0; index--) {
if (tokens[index].type !== " ") {
return index;
}
}
return undefined;
}
// :: array token -> array token
function stripTrailingComma(tokens) {
var res = [];
tokens.forEach(function (token, index) {
if (index > 0 && (token.type === "]" || token.type === "}")) {
// go backwards as long as there is whitespace, until first comma
var commaI = previousNWSToken(res, index - 1);
if (commaI !== undefined && commaI > 0 && res[commaI].type === ",") {
var preCommaI = previousNWSToken(res, commaI - 1);
if (preCommaI !== undefined && res[preCommaI].type !== "[" && res[preCommaI].type !== "{") {
res[commaI] = {
type: " ",
match: " ",
value: " ",
line: tokens[commaI].line,
};
}
}
}
res.push(token);
});
return res;
}
// :: string -> string
function transform(text) {
// Tokenize contents
var tokens = lexer(text);
// remove trailing commas
tokens = stripTrailingComma(tokens);
// concat stuff
return tokens.reduce(function (str, token) {
return str + token.match;
}, "");
}
// typify: type parseWarning = { message: string, line: nat }
// typify: type parseState = { pos : nat, warnings: array parseWarning }
// :: array parseToken -> parseState -> *
function popToken(tokens, state) {
var token = tokens[state.pos];
state.pos += 1;
if (!token) {
var line = tokens.length !== 0 ? tokens[tokens.length - 1].line : 1;
return { type: "eof", match: "", line: line }; // XXX: match should be value
}
return token;
}
// :: token -> string
function strToken(token) {
switch (token.type) {
case "atom":
case "string":
case "number":
return token.type + " " + token.match;
case "eof":
return "end-of-file";
default:
return "'" + token.type + "'";
}
}
// :: array token -> parseState -> undefined
function skipColon(tokens, state) {
var colon = popToken(tokens, state);
if (colon.type !== ":") {
var message = "Unexpected token: " + strToken(colon) + ", expected ':'";
if (state.tolerant) {
state.warnings.push({
message: message,
line: colon.line,
});
state.pos -= 1;
} else {
var err = new SyntaxError(message);
err.line = colon.line;
throw err;
}
}
}
// :: array token -> parseState -> (array string)? -> token
function skipPunctuation(tokens, state, valid) {
var punctuation = [",", ":", "]", "}"];
var token = popToken(tokens, state);
while (true) { // eslint-disable-line no-constant-condition
if (valid && valid.indexOf(token.type) !== -1) {
return token;
} else if (token.type === "eof") {
return token;
} else if (punctuation.indexOf(token.type) !== -1) {
var message = "Unexpected token: " + strToken(token) + ", expected '[', '{', number, string or atom";
if (state.tolerant) {
state.warnings.push({
message: message,
line: token.line,
});
token = popToken(tokens, state);
} else {
var err = new SyntaxError(message);
err.line = token.line;
throw err;
}
} else {
return token;
}
}
}
// :: parseState -> token -> string -> undefined
function raiseError(state, token, message) {
if (state.tolerant) {
state.warnings.push({
message: message,
line: token.line,
});
} else {
var err = new SyntaxError(message);
err.line = token.line;
throw err;
}
}
// :: parseState -> token -> string -> undefined
function raiseUnexpected(state, token, expected) {
raiseError(state, token, "Unexpected token: " + strToken(token) + ", expected " + expected);
}
// :: parseState -> {} -> parseToken -> undefined
function checkDuplicates(state, obj, token) {
var key = token.value;
if (state.duplicate && Object.prototype.hasOwnProperty.call(obj, key)) {
raiseError(state, token, "Duplicate key: " + key);
}
}
// XXX: too loosy signature
// :: parseState -> any -> any -> any -> undefined
function appendPair(state, obj, key, value) {
value = state.reviver ? state.reviver(key, value) : value;
if (value !== undefined) {
obj[key] = value;
}
}
// :: array parseToken -> parseState -> map -> undefined
function parsePair(tokens, state, obj) {
var token = skipPunctuation(tokens, state, [":"]);
var key;
var value;
if (token.type !== "string") {
raiseUnexpected(state, token, "string");
switch (token.type) {
case ":":
token = {
type: "string",
value: "null",
line: token.line,
};
state.pos -= 1;
break;
case "number":
case "atom":
token = {
type: "string",
value: "" + token.value,
line: token.line,
};
break;
case "[":
case "{":
state.pos -= 1;
value = parseAny(tokens, state); // eslint-disable-line no-use-before-define
appendPair(state, obj, "null", value);
return;
// no default
}
}
checkDuplicates(state, obj, token);
key = token.value;
skipColon(tokens, state);
value = parseAny(tokens, state); // eslint-disable-line no-use-before-define
appendPair(state, obj, key, value);
}
// :: array parseToken -> parseState -> array -> undefined
function parseElement(tokens, state, arr) {
var key = arr.length;
var value = parseAny(tokens, state); // eslint-disable-line no-use-before-define
arr[key] = state.reviver ? state.reviver("" + key, value) : value;
}
// :: array parseToken -> parseState -> {}
function parseObject(tokens, state) {
return parseMany(tokens, state, {}, { // eslint-disable-line no-use-before-define
skip: [":", "}"],
elementParser: parsePair,
elementName: "string",
endSymbol: "}",
});
}
// :: array parseToken -> parseState -> array
function parseArray(tokens, state) {
return parseMany(tokens, state, [], { // eslint-disable-line no-use-before-define
skip: ["]"],
elementParser: parseElement,
elementName: "json object",
endSymbol: "]",
});
}
// typify: type parseManyOpts = { skip: array tokenType, elementParser: fn, elementName: string, endSymbol: tokenType }
// :: t : array | {} => array parseToken -> parseState -> t -> parseManyOpts -> t
function parseMany(tokens, state, obj, opts) {
var token = skipPunctuation(tokens, state, opts.skip);
if (token.type === "eof") {
raiseUnexpected(state, token, "'" + opts.endSymbol + "' or " + opts.elementName);
token = {
type: opts.endSymbol,
line: token.line,
};
}
switch (token.type) {
case opts.endSymbol:
return obj;
default:
state.pos -= 1; // push the token back
opts.elementParser(tokens, state, obj);
break;
}
// Rest
while (true) { // eslint-disable-line no-constant-condition
token = popToken(tokens, state);
if (token.type !== opts.endSymbol && token.type !== ",") {
raiseUnexpected(state, token, "',' or '" + opts.endSymbol + "'");
token = {
type: token.type === "eof" ? opts.endSymbol : ",",
line: token.line,
};
state.pos -= 1;
}
switch (token.type) {
case opts.endSymbol:
return obj;
case ",":
opts.elementParser(tokens, state, obj);
break;
// no default
}
}
}
// :: array parseToken -> parseState -> any -> undefined
function endChecks(tokens, state, ret) {
if (state.pos < tokens.length) {
raiseError(state, tokens[state.pos],
"Unexpected token: " + strToken(tokens[state.pos]) + ", expected end-of-input");
}
// Throw error at the end
if (state.tolerant && state.warnings.length !== 0) {
var message = state.warnings.length === 1 ? state.warnings[0].message : state.warnings.length + " parse warnings";
var err = new SyntaxError(message);
err.line = state.warnings[0].line;
err.warnings = state.warnings;
err.obj = ret;
throw err;
}
}
// :: array parseToken -> parseState -> boolean? -> any
function parseAny(tokens, state, end) {
var token = skipPunctuation(tokens, state);
var ret;
if (token.type === "eof") {
raiseUnexpected(state, token, "json object");
}
switch (token.type) {
case "{":
ret = parseObject(tokens, state);
break;
case "[":
ret = parseArray(tokens, state);
break;
case "string":
case "number":
case "atom":
ret = token.value;
break;
// no default
}
if (end) {
ret = state.reviver ? state.reviver("", ret) : ret;
endChecks(tokens, state, ret);
}
return ret;
}
// :: string -> * -> any
function parse(text, opts) {
if (typeof opts === "function" || opts === undefined) {
return JSON.parse(transform(text), opts);
} else if (new Object(opts) !== opts) { // eslint-disable-line no-new-object
throw new TypeError("opts/reviver should be undefined, a function or an object");
}
opts.relaxed = opts.relaxed !== undefined ? opts.relaxed : true;
opts.warnings = opts.warnings || opts.tolerant || false;
opts.tolerant = opts.tolerant || false;
opts.duplicate = opts.duplicate || false;
if (!opts.warnings && !opts.relaxed) {
return JSON.parse(text, opts.reviver);
}
var tokens = opts.relaxed ? lexer(text) : strictLexer(text);
if (opts.relaxed) {
// Strip commas
tokens = stripTrailingComma(tokens);
}
if (opts.warnings) {
// Strip whitespace
tokens = tokens.filter(function (token) {
return token.type !== " ";
});
var state = { pos: 0, reviver: opts.reviver, tolerant: opts.tolerant, duplicate: opts.duplicate, warnings: [] };
return parseAny(tokens, state, true);
} else {
var newtext = tokens.reduce(function (str, token) {
return str + token.match;
}, "");
return JSON.parse(newtext, opts.reviver);
}
}
// :: any -> string -> ... -> string
function stringifyPair(obj, key) {
return JSON.stringify(key) + ":" + stringify(obj[key]); // eslint-disable-line no-use-before-define
}
// :: any -> ... -> string
function stringify(obj) {
switch (typeof obj) {
case "string":
case "number":
case "boolean":
return JSON.stringify(obj);
// no default
}
if (Array.isArray(obj)) {
return "[" + obj.map(stringify).join(",") + "]";
}
if (new Object(obj) === obj) { // eslint-disable-line no-new-object
var keys = Object.keys(obj);
keys.sort();
return "{" + keys.map(stringifyPair.bind(null, obj)) + "}";
}
return "null";
}
// Export stuff
var RJSON = {
transform: transform,
parse: parse,
stringify: stringify,
};
/* global window, module */
if (typeof module !== "undefined") {
module.exports = RJSON;
} else if (typeof window !== "undefined") {
window.RJSON = RJSON;
}
}());