json_parse.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. /*
  2. http://www.JSON.org/json_parse.js
  3. 2008-09-18
  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. /*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode,
  38. hasOwnProperty, message, n, name, push, r, t, text
  39. */
  40. define(function(require, exports, module) {
  41. "use strict";
  42. // This is a function that can parse a JSON text, producing a JavaScript
  43. // data structure. It is a simple, recursive descent parser. It does not use
  44. // eval or regular expressions, so it can be used as a model for implementing
  45. // a JSON parser in other languages.
  46. // We are defining the function inside of another function to avoid creating
  47. // global variables.
  48. var at, // The index of the current character
  49. ch, // The current character
  50. escapee = {
  51. '"': '"',
  52. '\\': '\\',
  53. '/': '/',
  54. b: '\b',
  55. f: '\f',
  56. n: '\n',
  57. r: '\r',
  58. t: '\t'
  59. },
  60. text,
  61. error = function (m) {
  62. // Call error when something is wrong.
  63. throw {
  64. name: 'SyntaxError',
  65. message: m,
  66. at: at,
  67. text: text
  68. };
  69. },
  70. next = function (c) {
  71. // If a c parameter is provided, verify that it matches the current character.
  72. if (c && c !== ch) {
  73. error("Expected '" + c + "' instead of '" + ch + "'");
  74. }
  75. // Get the next character. When there are no more characters,
  76. // return the empty string.
  77. ch = text.charAt(at);
  78. at += 1;
  79. return ch;
  80. },
  81. number = function () {
  82. // Parse a number value.
  83. var number,
  84. string = '';
  85. if (ch === '-') {
  86. string = '-';
  87. next('-');
  88. }
  89. while (ch >= '0' && ch <= '9') {
  90. string += ch;
  91. next();
  92. }
  93. if (ch === '.') {
  94. string += '.';
  95. while (next() && ch >= '0' && ch <= '9') {
  96. string += ch;
  97. }
  98. }
  99. if (ch === 'e' || ch === 'E') {
  100. string += ch;
  101. next();
  102. if (ch === '-' || ch === '+') {
  103. string += ch;
  104. next();
  105. }
  106. while (ch >= '0' && ch <= '9') {
  107. string += ch;
  108. next();
  109. }
  110. }
  111. number = +string;
  112. if (isNaN(number)) {
  113. error("Bad number");
  114. } else {
  115. return number;
  116. }
  117. },
  118. string = function () {
  119. // Parse a string value.
  120. var hex,
  121. i,
  122. string = '',
  123. uffff;
  124. // When parsing for string values, we must look for " and \ characters.
  125. if (ch === '"') {
  126. while (next()) {
  127. if (ch === '"') {
  128. next();
  129. return string;
  130. } else if (ch === '\\') {
  131. next();
  132. if (ch === 'u') {
  133. uffff = 0;
  134. for (i = 0; i < 4; i += 1) {
  135. hex = parseInt(next(), 16);
  136. if (!isFinite(hex)) {
  137. break;
  138. }
  139. uffff = uffff * 16 + hex;
  140. }
  141. string += String.fromCharCode(uffff);
  142. } else if (typeof escapee[ch] === 'string') {
  143. string += escapee[ch];
  144. } else {
  145. break;
  146. }
  147. } else {
  148. string += ch;
  149. }
  150. }
  151. }
  152. error("Bad string");
  153. },
  154. white = function () {
  155. // Skip whitespace.
  156. while (ch && ch <= ' ') {
  157. next();
  158. }
  159. },
  160. word = function () {
  161. // true, false, or null.
  162. switch (ch) {
  163. case 't':
  164. next('t');
  165. next('r');
  166. next('u');
  167. next('e');
  168. return true;
  169. case 'f':
  170. next('f');
  171. next('a');
  172. next('l');
  173. next('s');
  174. next('e');
  175. return false;
  176. case 'n':
  177. next('n');
  178. next('u');
  179. next('l');
  180. next('l');
  181. return null;
  182. }
  183. error("Unexpected '" + ch + "'");
  184. },
  185. value, // Place holder for the value function.
  186. array = function () {
  187. // Parse an array value.
  188. var array = [];
  189. if (ch === '[') {
  190. next('[');
  191. white();
  192. if (ch === ']') {
  193. next(']');
  194. return array; // empty array
  195. }
  196. while (ch) {
  197. array.push(value());
  198. white();
  199. if (ch === ']') {
  200. next(']');
  201. return array;
  202. }
  203. next(',');
  204. white();
  205. }
  206. }
  207. error("Bad array");
  208. },
  209. object = function () {
  210. // Parse an object value.
  211. var key,
  212. object = {};
  213. if (ch === '{') {
  214. next('{');
  215. white();
  216. if (ch === '}') {
  217. next('}');
  218. return object; // empty object
  219. }
  220. while (ch) {
  221. key = string();
  222. white();
  223. next(':');
  224. if (Object.hasOwnProperty.call(object, key)) {
  225. error('Duplicate key "' + key + '"');
  226. }
  227. object[key] = value();
  228. white();
  229. if (ch === '}') {
  230. next('}');
  231. return object;
  232. }
  233. next(',');
  234. white();
  235. }
  236. }
  237. error("Bad object");
  238. };
  239. value = function () {
  240. // Parse a JSON value. It could be an object, an array, a string, a number,
  241. // or a word.
  242. white();
  243. switch (ch) {
  244. case '{':
  245. return object();
  246. case '[':
  247. return array();
  248. case '"':
  249. return string();
  250. case '-':
  251. return number();
  252. default:
  253. return ch >= '0' && ch <= '9' ? number() : word();
  254. }
  255. };
  256. // Return the json_parse function. It will have access to all of the above
  257. // functions and variables.
  258. return function (source, reviver) {
  259. var result;
  260. text = source;
  261. at = 0;
  262. ch = ' ';
  263. result = value();
  264. white();
  265. if (ch) {
  266. error("Syntax error");
  267. }
  268. // If there is a reviver function, we recursively walk the new structure,
  269. // passing each name/value pair to the reviver function for possible
  270. // transformation, starting with a temporary root object that holds the result
  271. // in an empty key. If there is not a reviver function, we simply return the
  272. // result.
  273. return typeof reviver === 'function' ? function walk(holder, key) {
  274. var k, v, value = holder[key];
  275. if (value && typeof value === 'object') {
  276. for (k in value) {
  277. if (Object.hasOwnProperty.call(value, k)) {
  278. v = walk(value, k);
  279. if (v !== undefined) {
  280. value[k] = v;
  281. } else {
  282. delete value[k];
  283. }
  284. }
  285. }
  286. }
  287. return reviver.call(holder, key, value);
  288. }({'': result}, '') : result;
  289. };
  290. });