UNPKG

1.32 kBJavaScriptView Raw
1'use strict';
2
3// https://github.com/fastify/secure-json-parse
4// https://github.com/hapijs/bourne
5var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
6var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
7var JsonSigRx = /^["{[]|^-?[0-9][0-9.]*$/;
8
9function jsonParseTransform(key, value) {
10 if (key === '__proto__' || key === 'constructor') {
11 return;
12 }
13
14 return value;
15}
16
17function destr(val) {
18 if (typeof val !== 'string') {
19 return val;
20 }
21
22 var _lval = val.toLowerCase();
23
24 if (_lval === 'true') {
25 return true;
26 }
27
28 if (_lval === 'false') {
29 return false;
30 }
31
32 if (_lval === 'null') {
33 return null;
34 }
35
36 if (_lval === 'nan') {
37 return NaN;
38 }
39
40 if (_lval === 'infinity') {
41 return Infinity;
42 }
43
44 if (_lval === 'undefined') {
45 return undefined;
46 }
47
48 if (!JsonSigRx.test(val)) {
49 return val;
50 }
51
52 try {
53 if (suspectProtoRx.test(val) || suspectConstructorRx.test(val)) {
54 return JSON.parse(val, jsonParseTransform);
55 }
56
57 return JSON.parse(val);
58 } catch (_e) {
59 return val;
60 }
61}
62
63module.exports = destr;