json5.js 23 KB

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