json5.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. // json5.js
  2. // Modern JSON. See README.md for details.
  3. //
  4. // This file is based directly off of Douglas Crockford's json_parse.js:
  5. // https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
  6. var JSON5 = (typeof exports === 'object' ? exports : {});
  7. JSON5.parse = (function () {
  8. "use strict";
  9. // This is a function that can parse a JSON5 text, producing a JavaScript
  10. // data structure. It is a simple, recursive descent parser. It does not use
  11. // eval or regular expressions, so it can be used as a model for implementing
  12. // a JSON5 parser in other languages.
  13. // We are defining the function inside of another function to avoid creating
  14. // global variables.
  15. var at, // The index of the current character
  16. ch, // The current character
  17. escapee = {
  18. "'": "'",
  19. '"': '"',
  20. '\\': '\\',
  21. '/': '/',
  22. '\n': '', // Replace escaped newlines in strings w/ empty string
  23. b: '\b',
  24. f: '\f',
  25. n: '\n',
  26. r: '\r',
  27. t: '\t'
  28. },
  29. ws = [
  30. ' ',
  31. '\t',
  32. '\r',
  33. '\n',
  34. '\v',
  35. '\f',
  36. '\xA0',
  37. '\uFEFF'
  38. ],
  39. text,
  40. error = function (m) {
  41. // Call error when something is wrong.
  42. var error = new SyntaxError();
  43. error.message = m;
  44. error.at = at;
  45. error.text = text;
  46. throw error;
  47. },
  48. next = function (c) {
  49. // If a c parameter is provided, verify that it matches the current character.
  50. if (c && c !== ch) {
  51. error("Expected '" + c + "' instead of '" + ch + "'");
  52. }
  53. // Get the next character. When there are no more characters,
  54. // return the empty string.
  55. ch = text.charAt(at);
  56. at += 1;
  57. return ch;
  58. },
  59. peek = function () {
  60. // Get the next character without consuming it or
  61. // assigning it to the ch varaible.
  62. return text.charAt(at);
  63. },
  64. identifier = function () {
  65. // Parse an identifier. Normally, reserved words are disallowed here, but we
  66. // only use this for unquoted object keys, where reserved words are allowed,
  67. // so we don't check for those here. References:
  68. // - http://es5.github.com/#x7.6
  69. // - https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#Variables
  70. // - http://docstore.mik.ua/orelly/webprog/jscript/ch02_07.htm
  71. var key = ch;
  72. // Identifiers must start with a letter, _ or $.
  73. if ((ch !== '_' && ch !== '$') &&
  74. (ch < 'a' || ch > 'z') &&
  75. (ch < 'A' || ch > 'Z')) {
  76. error("Bad identifier");
  77. }
  78. // Subsequent characters can contain digits.
  79. while (next() && (
  80. ch === '_' || ch === '$' ||
  81. (ch >= 'a' && ch <= 'z') ||
  82. (ch >= 'A' && ch <= 'Z') ||
  83. (ch >= '0' && ch <= '9'))) {
  84. key += ch;
  85. }
  86. return key;
  87. },
  88. number = function () {
  89. // Parse a number value.
  90. var number,
  91. sign = '',
  92. string = '',
  93. base = 10;
  94. if (ch === '-' || ch === '+') {
  95. sign = ch;
  96. next(ch);
  97. }
  98. // support for Infinity (could tweak to allow other words):
  99. if (ch === 'I') {
  100. number = word();
  101. if (typeof number !== 'number' || isNaN(number)) {
  102. error('Unexpected word for number');
  103. }
  104. return (sign === '-') ? -number : number;
  105. }
  106. // support for NaN
  107. if (ch === 'N' ) {
  108. number = word();
  109. if (!isNaN(number)) {
  110. error('expected word to be NaN');
  111. }
  112. // ignore sign as -NaN also is NaN
  113. return number;
  114. }
  115. if (ch === '0') {
  116. string += ch;
  117. next();
  118. if (ch === 'x' || ch === 'X') {
  119. string += ch;
  120. next();
  121. base = 16;
  122. } else if (ch >= '0' && ch <= '9') {
  123. error('Octal literal');
  124. }
  125. }
  126. switch (base) {
  127. case 10:
  128. while (ch >= '0' && ch <= '9' ) {
  129. string += ch;
  130. next();
  131. }
  132. if (ch === '.') {
  133. string += '.';
  134. while (next() && ch >= '0' && ch <= '9') {
  135. string += ch;
  136. }
  137. }
  138. if (ch === 'e' || ch === 'E') {
  139. string += ch;
  140. next();
  141. if (ch === '-' || ch === '+') {
  142. string += ch;
  143. next();
  144. }
  145. while (ch >= '0' && ch <= '9') {
  146. string += ch;
  147. next();
  148. }
  149. }
  150. break;
  151. case 16:
  152. while (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {
  153. string += ch;
  154. next();
  155. }
  156. break;
  157. }
  158. if(sign === '-') {
  159. number = -string;
  160. } else {
  161. number = +string;
  162. }
  163. if (!isFinite(number)) {
  164. error("Bad number");
  165. } else {
  166. return number;
  167. }
  168. },
  169. string = function () {
  170. // Parse a string value.
  171. var hex,
  172. i,
  173. string = '',
  174. delim, // double quote or single quote
  175. uffff;
  176. // When parsing for string values, we must look for ' or " and \ characters.
  177. if (ch === '"' || ch === "'") {
  178. delim = ch;
  179. while (next()) {
  180. if (ch === delim) {
  181. next();
  182. return string;
  183. } else if (ch === '\\') {
  184. next();
  185. if (ch === 'u') {
  186. uffff = 0;
  187. for (i = 0; i < 4; i += 1) {
  188. hex = parseInt(next(), 16);
  189. if (!isFinite(hex)) {
  190. break;
  191. }
  192. uffff = uffff * 16 + hex;
  193. }
  194. string += String.fromCharCode(uffff);
  195. } else if (ch === '\r') {
  196. if (peek() === '\n') {
  197. next();
  198. }
  199. } else if (typeof escapee[ch] === 'string') {
  200. string += escapee[ch];
  201. } else {
  202. break;
  203. }
  204. } else if (ch === '\n') {
  205. // unescaped newlines are invalid; see:
  206. // https://github.com/aseemk/json5/issues/24
  207. // invalid unescaped chars?
  208. break;
  209. } else {
  210. string += ch;
  211. }
  212. }
  213. }
  214. error("Bad string");
  215. },
  216. inlineComment = function () {
  217. // Skip an inline comment, assuming this is one. The current character should
  218. // be the second / character in the // pair that begins this inline comment.
  219. // To finish the inline comment, we look for a newline or the end of the text.
  220. if (ch !== '/') {
  221. error("Not an inline comment");
  222. }
  223. do {
  224. next();
  225. if (ch === '\n' || ch === '\r') {
  226. next();
  227. return;
  228. }
  229. } while (ch);
  230. },
  231. blockComment = function () {
  232. // Skip a block comment, assuming this is one. The current character should be
  233. // the * character in the /* pair that begins this block comment.
  234. // To finish the block comment, we look for an ending */ pair of characters,
  235. // but we also watch for the end of text before the comment is terminated.
  236. if (ch !== '*') {
  237. error("Not a block comment");
  238. }
  239. do {
  240. next();
  241. while (ch === '*') {
  242. next('*');
  243. if (ch === '/') {
  244. next('/');
  245. return;
  246. }
  247. }
  248. } while (ch);
  249. error("Unterminated block comment");
  250. },
  251. comment = function () {
  252. // Skip a comment, whether inline or block-level, assuming this is one.
  253. // Comments always begin with a / character.
  254. if (ch !== '/') {
  255. error("Not a comment");
  256. }
  257. next('/');
  258. if (ch === '/') {
  259. inlineComment();
  260. } else if (ch === '*') {
  261. blockComment();
  262. } else {
  263. error("Unrecognized comment");
  264. }
  265. },
  266. white = function () {
  267. // Skip whitespace and comments.
  268. // Note that we're detecting comments by only a single / character.
  269. // This works since regular expressions are not valid JSON(5), but this will
  270. // break if there are other valid values that begin with a / character!
  271. while (ch) {
  272. if (ch === '/') {
  273. comment();
  274. } else if (ws.indexOf(ch) >= 0) {
  275. next();
  276. } else {
  277. return;
  278. }
  279. }
  280. },
  281. word = function () {
  282. // true, false, or null.
  283. switch (ch) {
  284. case 't':
  285. next('t');
  286. next('r');
  287. next('u');
  288. next('e');
  289. return true;
  290. case 'f':
  291. next('f');
  292. next('a');
  293. next('l');
  294. next('s');
  295. next('e');
  296. return false;
  297. case 'n':
  298. next('n');
  299. next('u');
  300. next('l');
  301. next('l');
  302. return null;
  303. case 'I':
  304. next('I');
  305. next('n');
  306. next('f');
  307. next('i');
  308. next('n');
  309. next('i');
  310. next('t');
  311. next('y');
  312. return Infinity;
  313. case 'N':
  314. next( 'N' );
  315. next( 'a' );
  316. next( 'N' );
  317. return NaN;
  318. }
  319. error("Unexpected '" + ch + "'");
  320. },
  321. value, // Place holder for the value function.
  322. array = function () {
  323. // Parse an array value.
  324. var array = [];
  325. if (ch === '[') {
  326. next('[');
  327. white();
  328. while (ch) {
  329. if (ch === ']') {
  330. next(']');
  331. return array; // Potentially empty array
  332. }
  333. // ES5 allows omitting elements in arrays, e.g. [,] and
  334. // [,null]. We don't allow this in JSON5.
  335. if (ch === ',') {
  336. error("Missing array element");
  337. } else {
  338. array.push(value());
  339. }
  340. white();
  341. // If there's no comma after this value, this needs to
  342. // be the end of the array.
  343. if (ch !== ',') {
  344. next(']');
  345. return array;
  346. }
  347. next(',');
  348. white();
  349. }
  350. }
  351. error("Bad array");
  352. },
  353. object = function () {
  354. // Parse an object value.
  355. var key,
  356. object = {};
  357. if (ch === '{') {
  358. next('{');
  359. white();
  360. while (ch) {
  361. if (ch === '}') {
  362. next('}');
  363. return object; // Potentially empty object
  364. }
  365. // Keys can be unquoted. If they are, they need to be
  366. // valid JS identifiers.
  367. if (ch === '"' || ch === "'") {
  368. key = string();
  369. } else {
  370. key = identifier();
  371. }
  372. white();
  373. next(':');
  374. object[key] = value();
  375. white();
  376. // If there's no comma after this pair, this needs to be
  377. // the end of the object.
  378. if (ch !== ',') {
  379. next('}');
  380. return object;
  381. }
  382. next(',');
  383. white();
  384. }
  385. }
  386. error("Bad object");
  387. };
  388. value = function () {
  389. // Parse a JSON value. It could be an object, an array, a string, a number,
  390. // or a word.
  391. white();
  392. switch (ch) {
  393. case '{':
  394. return object();
  395. case '[':
  396. return array();
  397. case '"':
  398. case "'":
  399. return string();
  400. case '-':
  401. case '+':
  402. case '.':
  403. return number();
  404. default:
  405. return ch >= '0' && ch <= '9' ? number() : word();
  406. }
  407. };
  408. // Return the json_parse function. It will have access to all of the above
  409. // functions and variables.
  410. return function (source, reviver) {
  411. var result;
  412. text = String(source);
  413. at = 0;
  414. ch = ' ';
  415. result = value();
  416. white();
  417. if (ch) {
  418. error("Syntax error");
  419. }
  420. // If there is a reviver function, we recursively walk the new structure,
  421. // passing each name/value pair to the reviver function for possible
  422. // transformation, starting with a temporary root object that holds the result
  423. // in an empty key. If there is not a reviver function, we simply return the
  424. // result.
  425. return typeof reviver === 'function' ? (function walk(holder, key) {
  426. var k, v, value = holder[key];
  427. if (value && typeof value === 'object') {
  428. for (k in value) {
  429. if (Object.prototype.hasOwnProperty.call(value, k)) {
  430. v = walk(value, k);
  431. if (v !== undefined) {
  432. value[k] = v;
  433. } else {
  434. delete value[k];
  435. }
  436. }
  437. }
  438. }
  439. return reviver.call(holder, key, value);
  440. }({'': result}, '')) : result;
  441. };
  442. }());
  443. // JSON5 stringify will not quote keys where appropriate
  444. JSON5.stringify = function (obj, replacer, space) {
  445. if (replacer && (typeof(replacer) !== "function" && !isArray(replacer))) {
  446. throw new Error('Replacer must be a function or an array');
  447. }
  448. var getReplacedValueOrUndefined = function(holder, key, isTopLevel) {
  449. var value = holder[key];
  450. // Replace the value with its toJSON value first, if possible
  451. if (value && value.toJSON && typeof value.toJSON === "function") {
  452. value = value.toJSON();
  453. }
  454. // If the user-supplied replacer if a function, call it. If it's an array, check objects' string keys for
  455. // presence in the array (removing the key/value pair from the resulting JSON if the key is missing).
  456. if (typeof(replacer) === "function") {
  457. return replacer.call(holder, key, value);
  458. } else if(replacer) {
  459. if (isTopLevel || isArray(holder) || replacer.indexOf(key) >= 0) {
  460. return value;
  461. } else {
  462. return undefined;
  463. }
  464. } else {
  465. return value;
  466. }
  467. };
  468. function isWordChar(char) {
  469. return (char >= 'a' && char <= 'z') ||
  470. (char >= 'A' && char <= 'Z') ||
  471. (char >= '0' && char <= '9') ||
  472. char === '_' || char === '$';
  473. }
  474. function isWordStart(char) {
  475. return (char >= 'a' && char <= 'z') ||
  476. (char >= 'A' && char <= 'Z') ||
  477. char === '_' || char === '$';
  478. }
  479. function isWord(key) {
  480. if (typeof key !== 'string') {
  481. return false;
  482. }
  483. if (!isWordStart(key[0])) {
  484. return false;
  485. }
  486. var i = 1, length = key.length;
  487. while (i < length) {
  488. if (!isWordChar(key[i])) {
  489. return false;
  490. }
  491. i++;
  492. }
  493. return true;
  494. }
  495. // export for use in tests
  496. JSON5.isWord = isWord;
  497. // polyfills
  498. function isArray(obj) {
  499. if (Array.isArray) {
  500. return Array.isArray(obj);
  501. } else {
  502. return Object.prototype.toString.call(obj) === '[object Array]';
  503. }
  504. }
  505. function isDate(obj) {
  506. return Object.prototype.toString.call(obj) === '[object Date]';
  507. }
  508. isNaN = isNaN || function(val) {
  509. return typeof val === 'number' && val !== val;
  510. };
  511. var objStack = [];
  512. function checkForCircular(obj) {
  513. for (var i = 0; i < objStack.length; i++) {
  514. if (objStack[i] === obj) {
  515. throw new TypeError("Converting circular structure to JSON");
  516. }
  517. }
  518. }
  519. function makeIndent(str, num, noNewLine) {
  520. if (!str) {
  521. return "";
  522. }
  523. // indentation no more than 10 chars
  524. if (str.length > 10) {
  525. str = str.substring(0, 10);
  526. }
  527. var indent = noNewLine ? "" : "\n";
  528. for (var i = 0; i < num; i++) {
  529. indent += str;
  530. }
  531. return indent;
  532. }
  533. var indentStr;
  534. if (space) {
  535. if (typeof space === "string") {
  536. indentStr = space;
  537. } else if (typeof space === "number" && space >= 0) {
  538. indentStr = makeIndent(" ", space, true);
  539. } else {
  540. // ignore space parameter
  541. }
  542. }
  543. // Copied from Crokford's implementation of JSON
  544. // See https://github.com/douglascrockford/JSON-js/blob/e39db4b7e6249f04a195e7dd0840e610cc9e941e/json2.js#L195
  545. // Begin
  546. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  547. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  548. meta = { // table of character substitutions
  549. '\b': '\\b',
  550. '\t': '\\t',
  551. '\n': '\\n',
  552. '\f': '\\f',
  553. '\r': '\\r',
  554. '"' : '\\"',
  555. '\\': '\\\\'
  556. };
  557. function escapeString(string) {
  558. // If the string contains no control characters, no quote characters, and no
  559. // backslash characters, then we can safely slap some quotes around it.
  560. // Otherwise we must also replace the offending characters with safe escape
  561. // sequences.
  562. escapable.lastIndex = 0;
  563. return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
  564. var c = meta[a];
  565. return typeof c === 'string' ?
  566. c :
  567. '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  568. }) + '"' : '"' + string + '"';
  569. }
  570. // End
  571. function internalStringify(holder, key, isTopLevel) {
  572. var buffer, res;
  573. // Replace the value, if necessary
  574. var obj_part = getReplacedValueOrUndefined(holder, key, isTopLevel);
  575. if (obj_part && !isDate(obj_part)) {
  576. // unbox objects
  577. // don't unbox dates, since will turn it into number
  578. obj_part = obj_part.valueOf();
  579. }
  580. switch(typeof obj_part) {
  581. case "boolean":
  582. return obj_part.toString();
  583. case "number":
  584. if (isNaN(obj_part) || !isFinite(obj_part)) {
  585. return "null";
  586. }
  587. return obj_part.toString();
  588. case "string":
  589. return escapeString(obj_part.toString());
  590. case "object":
  591. if (obj_part === null) {
  592. return "null";
  593. } else if (isArray(obj_part)) {
  594. checkForCircular(obj_part);
  595. buffer = "[";
  596. objStack.push(obj_part);
  597. for (var i = 0; i < obj_part.length; i++) {
  598. res = internalStringify(obj_part, i, false);
  599. buffer += makeIndent(indentStr, objStack.length);
  600. if (res === null || typeof res === "undefined") {
  601. buffer += "null";
  602. } else {
  603. buffer += res;
  604. }
  605. if (i < obj_part.length-1) {
  606. buffer += ",";
  607. } else if (indentStr) {
  608. buffer += "\n";
  609. }
  610. }
  611. objStack.pop();
  612. buffer += makeIndent(indentStr, objStack.length, true) + "]";
  613. } else {
  614. checkForCircular(obj_part);
  615. buffer = "{";
  616. var nonEmpty = false;
  617. objStack.push(obj_part);
  618. for (var prop in obj_part) {
  619. if (obj_part.hasOwnProperty(prop)) {
  620. var value = internalStringify(obj_part, prop, false);
  621. isTopLevel = false;
  622. if (typeof value !== "undefined" && value !== null) {
  623. buffer += makeIndent(indentStr, objStack.length);
  624. nonEmpty = true;
  625. var key = isWord(prop) ? prop : escapeString(prop);
  626. buffer += key + ":" + (indentStr ? ' ' : '') + value + ",";
  627. }
  628. }
  629. }
  630. objStack.pop();
  631. if (nonEmpty) {
  632. buffer = buffer.substring(0, buffer.length-1) + makeIndent(indentStr, objStack.length) + "}";
  633. } else {
  634. buffer = '{}';
  635. }
  636. }
  637. return buffer;
  638. default:
  639. // functions and undefined should be ignored
  640. return undefined;
  641. }
  642. }
  643. // special case...when undefined is used inside of
  644. // a compound object/array, return null.
  645. // but when top-level, return undefined
  646. var topLevelHolder = {"":obj};
  647. if (obj === undefined) {
  648. return getReplacedValueOrUndefined(topLevelHolder, '', true);
  649. }
  650. return internalStringify(topLevelHolder, '', true);
  651. };