json_parse_state.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /*
  2. json_parse_state.js
  3. 2015-05-02
  4. Public Domain.
  5. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  6. This file creates a json_parse function.
  7. json_parse(text, reviver)
  8. This method parses a JSON text to produce an object or array.
  9. It can throw a SyntaxError exception.
  10. The optional reviver parameter is a function that can filter and
  11. transform the results. It receives each of the keys and values,
  12. and its return value is used instead of the original value.
  13. If it returns what it received, then the structure is not modified.
  14. If it returns undefined then the member is deleted.
  15. Example:
  16. // Parse the text. Values that look like ISO date strings will
  17. // be converted to Date objects.
  18. myData = json_parse(text, function (key, value) {
  19. var a;
  20. if (typeof value === 'string') {
  21. a =
  22. /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
  23. if (a) {
  24. return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
  25. +a[5], +a[6]));
  26. }
  27. }
  28. return value;
  29. });
  30. This is a reference implementation. You are free to copy, modify, or
  31. redistribute.
  32. This code should be minified before deployment.
  33. See http://javascript.crockford.com/jsmin.html
  34. USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
  35. NOT CONTROL.
  36. */
  37. /*jslint for */
  38. /*property
  39. acomma, avalue, b, call, colon, container, exec, f, false, firstavalue,
  40. firstokey, fromCharCode, go, hasOwnProperty, key, length, n, null, ocomma,
  41. okey, ovalue, pop, prototype, push, r, replace, slice, state, t, test,
  42. true
  43. */
  44. var json_parse = (function () {
  45. "use strict";
  46. // This function creates a JSON parse function that uses a state machine rather
  47. // than the dangerous eval function to parse a JSON text.
  48. var state, // The state of the parser, one of
  49. // 'go' The starting state
  50. // 'ok' The final, accepting state
  51. // 'firstokey' Ready for the first key of the object or
  52. // the closing of an empty object
  53. // 'okey' Ready for the next key of the object
  54. // 'colon' Ready for the colon
  55. // 'ovalue' Ready for the value half of a key/value pair
  56. // 'ocomma' Ready for a comma or closing }
  57. // 'firstavalue' Ready for the first value of an array or
  58. // an empty array
  59. // 'avalue' Ready for the next value of an array
  60. // 'acomma' Ready for a comma or closing ]
  61. stack, // The stack, for controlling nesting.
  62. container, // The current container object or array
  63. key, // The current key
  64. value, // The current value
  65. escapes = { // Escapement translation table
  66. '\\': '\\',
  67. '"': '"',
  68. '/': '/',
  69. 't': '\t',
  70. 'n': '\n',
  71. 'r': '\r',
  72. 'f': '\f',
  73. 'b': '\b'
  74. },
  75. string = { // The actions for string tokens
  76. go: function () {
  77. state = 'ok';
  78. },
  79. firstokey: function () {
  80. key = value;
  81. state = 'colon';
  82. },
  83. okey: function () {
  84. key = value;
  85. state = 'colon';
  86. },
  87. ovalue: function () {
  88. state = 'ocomma';
  89. },
  90. firstavalue: function () {
  91. state = 'acomma';
  92. },
  93. avalue: function () {
  94. state = 'acomma';
  95. }
  96. },
  97. number = { // The actions for number tokens
  98. go: function () {
  99. state = 'ok';
  100. },
  101. ovalue: function () {
  102. state = 'ocomma';
  103. },
  104. firstavalue: function () {
  105. state = 'acomma';
  106. },
  107. avalue: function () {
  108. state = 'acomma';
  109. }
  110. },
  111. action = {
  112. // The action table describes the behavior of the machine. It contains an
  113. // object for each token. Each object contains a method that is called when
  114. // a token is matched in a state. An object will lack a method for illegal
  115. // states.
  116. '{': {
  117. go: function () {
  118. stack.push({state: 'ok'});
  119. container = {};
  120. state = 'firstokey';
  121. },
  122. ovalue: function () {
  123. stack.push({container: container, state: 'ocomma', key: key});
  124. container = {};
  125. state = 'firstokey';
  126. },
  127. firstavalue: function () {
  128. stack.push({container: container, state: 'acomma'});
  129. container = {};
  130. state = 'firstokey';
  131. },
  132. avalue: function () {
  133. stack.push({container: container, state: 'acomma'});
  134. container = {};
  135. state = 'firstokey';
  136. }
  137. },
  138. '}': {
  139. firstokey: function () {
  140. var pop = stack.pop();
  141. value = container;
  142. container = pop.container;
  143. key = pop.key;
  144. state = pop.state;
  145. },
  146. ocomma: function () {
  147. var pop = stack.pop();
  148. container[key] = value;
  149. value = container;
  150. container = pop.container;
  151. key = pop.key;
  152. state = pop.state;
  153. }
  154. },
  155. '[': {
  156. go: function () {
  157. stack.push({state: 'ok'});
  158. container = [];
  159. state = 'firstavalue';
  160. },
  161. ovalue: function () {
  162. stack.push({container: container, state: 'ocomma', key: key});
  163. container = [];
  164. state = 'firstavalue';
  165. },
  166. firstavalue: function () {
  167. stack.push({container: container, state: 'acomma'});
  168. container = [];
  169. state = 'firstavalue';
  170. },
  171. avalue: function () {
  172. stack.push({container: container, state: 'acomma'});
  173. container = [];
  174. state = 'firstavalue';
  175. }
  176. },
  177. ']': {
  178. firstavalue: function () {
  179. var pop = stack.pop();
  180. value = container;
  181. container = pop.container;
  182. key = pop.key;
  183. state = pop.state;
  184. },
  185. acomma: function () {
  186. var pop = stack.pop();
  187. container.push(value);
  188. value = container;
  189. container = pop.container;
  190. key = pop.key;
  191. state = pop.state;
  192. }
  193. },
  194. ':': {
  195. colon: function () {
  196. if (Object.hasOwnProperty.call(container, key)) {
  197. throw new SyntaxError('Duplicate key "' + key + '"');
  198. }
  199. state = 'ovalue';
  200. }
  201. },
  202. ',': {
  203. ocomma: function () {
  204. container[key] = value;
  205. state = 'okey';
  206. },
  207. acomma: function () {
  208. container.push(value);
  209. state = 'avalue';
  210. }
  211. },
  212. 'true': {
  213. go: function () {
  214. value = true;
  215. state = 'ok';
  216. },
  217. ovalue: function () {
  218. value = true;
  219. state = 'ocomma';
  220. },
  221. firstavalue: function () {
  222. value = true;
  223. state = 'acomma';
  224. },
  225. avalue: function () {
  226. value = true;
  227. state = 'acomma';
  228. }
  229. },
  230. 'false': {
  231. go: function () {
  232. value = false;
  233. state = 'ok';
  234. },
  235. ovalue: function () {
  236. value = false;
  237. state = 'ocomma';
  238. },
  239. firstavalue: function () {
  240. value = false;
  241. state = 'acomma';
  242. },
  243. avalue: function () {
  244. value = false;
  245. state = 'acomma';
  246. }
  247. },
  248. 'null': {
  249. go: function () {
  250. value = null;
  251. state = 'ok';
  252. },
  253. ovalue: function () {
  254. value = null;
  255. state = 'ocomma';
  256. },
  257. firstavalue: function () {
  258. value = null;
  259. state = 'acomma';
  260. },
  261. avalue: function () {
  262. value = null;
  263. state = 'acomma';
  264. }
  265. }
  266. };
  267. function debackslashify(text) {
  268. // Remove and replace any backslash escapement.
  269. return text.replace(/\\(?:u(.{4})|([^u]))/g, function (ignore, b, c) {
  270. return b
  271. ? String.fromCharCode(parseInt(b, 16))
  272. : escapes[c];
  273. });
  274. }
  275. return function (source, reviver) {
  276. // A regular expression is used to extract tokens from the JSON text.
  277. // The extraction process is cautious.
  278. var result,
  279. tx = /^[\u0020\t\n\r]*(?:([,:\[\]{}]|true|false|null)|(-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)|"((?:[^\r\n\t\\\"]|\\(?:["\\\/trnfb]|u[0-9a-fA-F]{4}))*)")/;
  280. // Set the starting state.
  281. state = 'go';
  282. // The stack records the container, key, and state for each object or array
  283. // that contains another object or array while processing nested structures.
  284. stack = [];
  285. // If any error occurs, we will catch it and ultimately throw a syntax error.
  286. try {
  287. // For each token...
  288. while (true) {
  289. result = tx.exec(source);
  290. if (!result) {
  291. break;
  292. }
  293. // result is the result array from matching the tokenizing regular expression.
  294. // result[0] contains everything that matched, including any initial whitespace.
  295. // result[1] contains any punctuation that was matched, or true, false, or null.
  296. // result[2] contains a matched number, still in string form.
  297. // result[3] contains a matched string, without quotes but with escapement.
  298. if (result[1]) {
  299. // Token: Execute the action for this state and token.
  300. action[result[1]][state]();
  301. } else if (result[2]) {
  302. // Number token: Convert the number string into a number value and execute
  303. // the action for this state and number.
  304. value = +result[2];
  305. number[state]();
  306. } else {
  307. // String token: Replace the escapement sequences and execute the action for
  308. // this state and string.
  309. value = debackslashify(result[3]);
  310. string[state]();
  311. }
  312. // Remove the token from the string. The loop will continue as long as there
  313. // are tokens. This is a slow process, but it allows the use of ^ matching,
  314. // which assures that no illegal tokens slip through.
  315. source = source.slice(result[0].length);
  316. }
  317. // If we find a state/token combination that is illegal, then the action will
  318. // cause an error. We handle the error by simply changing the state.
  319. } catch (e) {
  320. state = e;
  321. }
  322. // The parsing is finished. If we are not in the final 'ok' state, or if the
  323. // remaining source contains anything except whitespace, then we did not have
  324. //a well-formed JSON text.
  325. if (state !== 'ok' || (/[^\u0020\t\n\r]/.test(source))) {
  326. throw state instanceof SyntaxError
  327. ? state
  328. : new SyntaxError('JSON');
  329. }
  330. // If there is a reviver function, we recursively walk the new structure,
  331. // passing each name/value pair to the reviver function for possible
  332. // transformation, starting with a temporary root object that holds the current
  333. // value in an empty key. If there is not a reviver function, we simply return
  334. // that value.
  335. return typeof reviver === 'function'
  336. ? (function walk(holder, key) {
  337. var k, v, value = holder[key];
  338. if (value && typeof value === 'object') {
  339. for (k in value) {
  340. if (Object.prototype.hasOwnProperty.call(value, k)) {
  341. v = walk(value, k);
  342. if (v !== undefined) {
  343. value[k] = v;
  344. } else {
  345. delete value[k];
  346. }
  347. }
  348. }
  349. }
  350. return reviver.call(holder, key, value);
  351. }({'': value}, ''))
  352. : value;
  353. };
  354. }());