fromJson.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // wrapped by build app
  2. define("dojox/secure/fromJson", ["dijit","dojo","dojox"], function(dijit,dojo,dojox){
  3. dojo.provide("dojox.secure.fromJson");
  4. // Used with permission from Mike Samuel of Google (has CCLA), from the json-sans-eval project:
  5. // http://code.google.com/p/json-sans-eval/
  6. // Mike Samuel <mikesamuel@gmail.com>
  7. dojox.secure.fromJson = typeof JSON != "undefined" ? JSON.parse :
  8. // summary:
  9. // Parses a string of well-formed JSON text.
  10. // description:
  11. // Parses a string of well-formed JSON text. If the input is not well-formed,
  12. // then behavior is undefined, but it is
  13. // deterministic and is guaranteed not to modify any object other than its
  14. // return value.
  15. //
  16. // This does not use `eval` so is less likely to have obscure security bugs than
  17. // json2.js.
  18. // It is optimized for speed, so is much faster than json_parse.js.
  19. //
  20. // This library should be used whenever security is a concern (when JSON may
  21. // come from an untrusted source), speed is a concern, and erroring on malformed
  22. // JSON is *not* a concern.
  23. //
  24. // json2.js is very fast, but potentially insecure since it calls `eval` to
  25. // parse JSON data, so an attacker might be able to supply strange JS that
  26. // looks like JSON, but that executes arbitrary javascript.
  27. //
  28. // To configure dojox.secure.fromJson as the JSON parser for all Dojo
  29. // JSON parsing, simply do:
  30. // | dojo.require("dojox.secure.fromJson");
  31. // | dojo.fromJson = dojox.secure.fromJson;
  32. // or alternately you could configure dojox.secure.fromJson to only handle
  33. // XHR responses:
  34. // | dojo._contentHandlers.json = function(xhr){
  35. // | return dojox.secure.fromJson.fromJson(xhr.responseText);
  36. // | };
  37. //
  38. // json: String
  39. // per RFC 4627
  40. // optReviver: Function (this:Object, string, *)
  41. // optional function
  42. // that reworks JSON objects post-parse per Chapter 15.12 of EcmaScript3.1.
  43. // If supplied, the function is called with a string key, and a value.
  44. // The value is the property of 'this'. The reviver should return
  45. // the value to use in its place. So if dates were serialized as
  46. // {@code { "type": "Date", "time": 1234 }}, then a reviver might look like
  47. // {@code
  48. // function (key, value) {
  49. // if (value && typeof value === 'object' && 'Date' === value.type) {
  50. // return new Date(value.time);
  51. // } else {
  52. // return value;
  53. // }
  54. // }}.
  55. // If the reviver returns {@code undefined} then the property named by key
  56. // will be deleted from its container.
  57. // {@code this} is bound to the object containing the specified property.
  58. // returns: {Object|Array}
  59. (function () {
  60. var number
  61. = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
  62. var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
  63. + '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
  64. var string = '(?:\"' + oneChar + '*\")';
  65. // Will match a value in a well-formed JSON file.
  66. // If the input is not well-formed, may match strangely, but not in an unsafe
  67. // way.
  68. // Since this only matches value tokens, it does not match whitespace, colons,
  69. // or commas.
  70. var jsonToken = new RegExp(
  71. '(?:false|true|null|[\\{\\}\\[\\]]'
  72. + '|' + number
  73. + '|' + string
  74. + ')', 'g');
  75. // Matches escape sequences in a string literal
  76. var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');
  77. // Decodes escape sequences in object literals
  78. var escapes = {
  79. '"': '"',
  80. '/': '/',
  81. '\\': '\\',
  82. 'b': '\b',
  83. 'f': '\f',
  84. 'n': '\n',
  85. 'r': '\r',
  86. 't': '\t'
  87. };
  88. function unescapeOne(_, ch, hex) {
  89. return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
  90. }
  91. // A non-falsy value that coerces to the empty string when used as a key.
  92. var EMPTY_STRING = new String('');
  93. var SLASH = '\\';
  94. // Constructor to use based on an open token.
  95. var firstTokenCtors = { '{': Object, '[': Array };
  96. var hop = Object.hasOwnProperty;
  97. return function (json, opt_reviver) {
  98. // Split into tokens
  99. var toks = json.match(jsonToken);
  100. // Construct the object to return
  101. var result;
  102. var tok = toks[0];
  103. var topLevelPrimitive = false;
  104. if ('{' === tok) {
  105. result = {};
  106. } else if ('[' === tok) {
  107. result = [];
  108. } else {
  109. // The RFC only allows arrays or objects at the top level, but the JSON.parse
  110. // defined by the EcmaScript 5 draft does allow strings, booleans, numbers, and null
  111. // at the top level.
  112. result = [];
  113. topLevelPrimitive = true;
  114. }
  115. // If undefined, the key in an object key/value record to use for the next
  116. // value parsed.
  117. var key;
  118. // Loop over remaining tokens maintaining a stack of uncompleted objects and
  119. // arrays.
  120. var stack = [result];
  121. for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) {
  122. tok = toks[i];
  123. var cont;
  124. switch (tok.charCodeAt(0)) {
  125. default: // sign or digit
  126. cont = stack[0];
  127. cont[key || cont.length] = +(tok);
  128. key = void 0;
  129. break;
  130. case 0x22: // '"'
  131. tok = tok.substring(1, tok.length - 1);
  132. if (tok.indexOf(SLASH) !== -1) {
  133. tok = tok.replace(escapeSequence, unescapeOne);
  134. }
  135. cont = stack[0];
  136. if (!key) {
  137. if (cont instanceof Array) {
  138. key = cont.length;
  139. } else {
  140. key = tok || EMPTY_STRING; // Use as key for next value seen.
  141. break;
  142. }
  143. }
  144. cont[key] = tok;
  145. key = void 0;
  146. break;
  147. case 0x5b: // '['
  148. cont = stack[0];
  149. stack.unshift(cont[key || cont.length] = []);
  150. key = void 0;
  151. break;
  152. case 0x5d: // ']'
  153. stack.shift();
  154. break;
  155. case 0x66: // 'f'
  156. cont = stack[0];
  157. cont[key || cont.length] = false;
  158. key = void 0;
  159. break;
  160. case 0x6e: // 'n'
  161. cont = stack[0];
  162. cont[key || cont.length] = null;
  163. key = void 0;
  164. break;
  165. case 0x74: // 't'
  166. cont = stack[0];
  167. cont[key || cont.length] = true;
  168. key = void 0;
  169. break;
  170. case 0x7b: // '{'
  171. cont = stack[0];
  172. stack.unshift(cont[key || cont.length] = {});
  173. key = void 0;
  174. break;
  175. case 0x7d: // '}'
  176. stack.shift();
  177. break;
  178. }
  179. }
  180. // Fail if we've got an uncompleted object.
  181. if (topLevelPrimitive) {
  182. if (stack.length !== 1) { throw new Error(); }
  183. result = result[0];
  184. } else {
  185. if (stack.length) { throw new Error(); }
  186. }
  187. if (opt_reviver) {
  188. // Based on walk as implemented in http://www.json.org/json2.js
  189. var walk = function (holder, key) {
  190. var value = holder[key];
  191. if (value && typeof value === 'object') {
  192. var toDelete = null;
  193. for (var k in value) {
  194. if (hop.call(value, k) && value !== holder) {
  195. // Recurse to properties first. This has the effect of causing
  196. // the reviver to be called on the object graph depth-first.
  197. // Since 'this' is bound to the holder of the property, the
  198. // reviver can access sibling properties of k including ones
  199. // that have not yet been revived.
  200. // The value returned by the reviver is used in place of the
  201. // current value of property k.
  202. // If it returns undefined then the property is deleted.
  203. var v = walk(value, k);
  204. if (v !== void 0) {
  205. value[k] = v;
  206. } else {
  207. // Deleting properties inside the loop has vaguely defined
  208. // semantics in ES3 and ES3.1.
  209. if (!toDelete) { toDelete = []; }
  210. toDelete.push(k);
  211. }
  212. }
  213. }
  214. if (toDelete) {
  215. for (var i = toDelete.length; --i >= 0;) {
  216. delete value[toDelete[i]];
  217. }
  218. }
  219. }
  220. return opt_reviver.call(holder, key, value);
  221. };
  222. result = walk({ '': result }, '');
  223. }
  224. return result;
  225. };
  226. })();
  227. });