json5.js 24 KB

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