/json2.asp

http://github.com/jayhealey/Classic-ASP-class-for-PostmarkApp · ASP · 863 lines · 589 code · 221 blank · 53 comment · 96 complexity · 10b86763a115d9ca98ee6030616b85f6 MD5 · raw file

  1. <script language="Javascript" runat="server">
  2. /*
  3. File: json2.asp
  4. AXE(ASP Xtreme Evolution) JSON parser based on Douglas Crockford json2.js.
  5. This class is the result of Classic ASP JSON topic revisited by Fabio Zendhi
  6. Nagao (nagaozen). JSON2.ASP is a better option over JSON.ASP because it embraces
  7. the AXE philosophy of real collaboration over the languages. It works under the
  8. original json parser, so this class is strict in the standard rules, plus it
  9. brings more of the Javascript json feeling to other ASP languages (eg. no more
  10. oJson.getElement("foo") stuff, just oJson.foo and you get it).
  11. License:
  12. This file is part of ASP Xtreme Evolution.
  13. Copyright (C) 2007-2010 Fabio Zendhi Nagao
  14. ASP Xtreme Evolution is free software: you can redistribute it and/or modify
  15. it under the terms of the GNU Lesser General Public License as published by
  16. the Free Software Foundation, either version 3 of the License, or
  17. (at your option) any later version.
  18. ASP Xtreme Evolution is distributed in the hope that it will be useful,
  19. but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. GNU Lesser General Public License for more details.
  22. You should have received a copy of the GNU Lesser General Public License
  23. along with ASP Xtreme Evolution. If not, see <http://www.gnu.org/licenses/>.
  24. Class: JSON
  25. JSON (Javascript Object Notation) is a lightweight data-interchange format. It
  26. is easy for humans to read and write. It is easy for machines to parse and
  27. generate. It is based on a subset of the Javascript Programming Language,
  28. Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is
  29. completely language independent but uses conventions that are familiar to
  30. programmers of the C-family of languages, including C, C++, C#, Java,
  31. Javascript, Perl, Python, and many others. These properties make JSON an ideal
  32. data-interchange language.
  33. Notes:
  34. - Javascript extensions concept inspired by Troy Foster JSON2.ASP work <http://tforster.wik.is/ASP_Classic_Practices_For_The_21st_Century/JSON4ASP>.
  35. - Javascript JSON parser is the Douglas Crockford json2.js <http://www.JSON.org/json2.js>, without the first line alert(...) and fixing "this.JSON = {};" to "JSON = {};" to make it JScript compatible.
  36. About:
  37. - Written by Fabio Zendhi Nagao <http://zend.lojcomm.com.br/> @ August 2010
  38. Function: parse
  39. This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception.
  40. Parameters:
  41. (string) - Valid JSON text.
  42. Returns:
  43. (mixed) - a Javascript value, usually an object or array.
  44. Example:
  45. (start code)
  46. dim Info : set Info = JSON.parse(join(array( _
  47. "{", _
  48. " ""firstname"": ""Fabio"",", _
  49. " ""lastname"": ""長尾"",", _
  50. " ""alive"": true,", _
  51. " ""age"": 27,", _
  52. " ""nickname"": ""nagaozen"",", _
  53. " ""fruits"": [", _
  54. " ""banana"",", _
  55. " ""orange"",", _
  56. " ""apple"",", _
  57. " ""papaya"",", _
  58. " ""pineapple""", _
  59. " ],", _
  60. " ""complex"": {", _
  61. " ""real"": 1,", _
  62. " ""imaginary"": 2", _
  63. " }", _
  64. "}" _
  65. )))
  66. Response.write(Info.firstname & vbNewline) ' prints Fabio
  67. Response.write(Info.alive & vbNewline) ' prints True
  68. Response.write(Info.age & vbNewline) ' prints 27
  69. Response.write(Info.fruits.get(0) & vbNewline) ' prints banana
  70. Response.write(Info.fruits.get(1) & vbNewline) ' prints orange
  71. Response.write(Info.complex.real & vbNewline) ' prints 1
  72. Response.write(Info.complex.imaginary & vbNewline) ' prints 2
  73. ' You can also enumerate object properties ...
  74. dim key : for each key in Info.keys()
  75. Response.write( key & vbNewline )
  76. next
  77. ' which prints:
  78. ' firstname
  79. ' lastname
  80. ' alive
  81. ' age
  82. ' nickname
  83. ' fruits
  84. ' complex
  85. set Info = nothing
  86. (end code)
  87. Function: stringify
  88. This method produces a JSON text from a Javascript value.
  89. Parameters:
  90. (mixed) - any Javascript value, usually an object or array.
  91. (mixed) - an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings.
  92. (mixed) - an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level.
  93. Returns:
  94. (string) - a string that contains the serialized JSON text.
  95. Example:
  96. (start code)
  97. dim Info : set Info = JSON.parse("{""firstname"":""Fabio"", ""lastname"":""長尾""}")
  98. Info.set "alive", true
  99. Info.set "age", 27
  100. Info.set "nickname", "nagaozen"
  101. Info.set "fruits", array("banana","orange","apple","papaya","pineapple")
  102. Info.set "complex", JSON.parse("{""real"":1, ""imaginary"":1}")
  103. Response.write( JSON.stringify(Info, null, 2) & vbNewline ) ' prints the text below:
  104. '{
  105. ' "firstname": "Fabio",
  106. ' "lastname": "長尾",
  107. ' "alive": true,
  108. ' "age": 27,
  109. ' "nickname": "nagaozen",
  110. ' "fruits": [
  111. ' "banana",
  112. ' "orange",
  113. ' "apple",
  114. ' "papaya",
  115. ' "pineapple"
  116. ' ],
  117. ' "complex": {
  118. ' "real": 1,
  119. ' "imaginary": 1
  120. ' }
  121. '}
  122. set Info = nothing
  123. (end code)
  124. Function: toXML
  125. This method produces a XML text from a Javascript value.
  126. Parameters:
  127. (mixed) - any Javascript value, usually an object or array.
  128. (string) - an optional parameter that determines what tag should be used as a container for the output. Defaults to none.
  129. Returns:
  130. (string) - a string that contains the serialized XML text.
  131. Example:
  132. (start code)
  133. dim Info : set Info = JSON.parse("{""firstname"":""Fabio"", ""lastname"":""長尾""}")
  134. Info.set "alive", true
  135. Info.set "age", 27
  136. Info.set "nickname", "nagaozen"
  137. Info.set "fruits", array("banana","orange","apple","papaya","pineapple")
  138. Info.set "complex", JSON.parse("{""real"":1, ""imaginary"":1}")
  139. Response.write( JSON.toXML(Info) & vbNewline ) ' prints the text below:
  140. '<firstname>Fabio</firstname>
  141. '<lastname>長尾</lastname>
  142. '<alive>true</alive>
  143. '<age>27</age>
  144. '<nickname>nagaozen</nickname>
  145. '<fruits>banana</fruits>
  146. '<fruits>orange</fruits>
  147. '<fruits>apple</fruits>
  148. '<fruits>papaya</fruits>
  149. '<fruits>pineapple</fruits>
  150. '<complex>
  151. ' <real>1</real>
  152. ' <imaginary>1</imaginary>
  153. '</complex>
  154. set Info = nothing
  155. (end code)
  156. */
  157. if(!Object.prototype.get) {
  158. Object.prototype.get = function(k) {
  159. return this[k];
  160. }
  161. }
  162. if(!Object.prototype.set) {
  163. Object.prototype.set = function(k,v) {
  164. if(typeof(v) == "unknown") {
  165. try {
  166. v = (new VBArray(v)).toArray();
  167. } catch(e) {
  168. return;
  169. }
  170. }
  171. this[k] = v;
  172. }
  173. }
  174. if(!Object.prototype["delete"]) {
  175. Object.prototype["delete"] = function(k) {
  176. delete this[k];
  177. }
  178. }
  179. if(!Object.prototype.keys) {
  180. Object.prototype.keys = function() {
  181. var d = new ActiveXObject("Scripting.Dictionary");
  182. for(var key in this) {
  183. if(this.hasOwnProperty(key)) {
  184. d.add(key, null);
  185. }
  186. }
  187. return d.keys();
  188. }
  189. }
  190. if(!String.prototype.sanitize) {
  191. String.prototype.sanitize = function(a, b) {
  192. var len = a.length,
  193. s = this;
  194. if(len !== b.length) throw new TypeError('Invalid procedure call. Both arrays should have the same size.');
  195. for(var i = 0; i < len; i++) {
  196. var re = new RegExp(a[i],'g');
  197. s = s.replace(re, b[i]);
  198. }
  199. return s;
  200. }
  201. }
  202. if(!String.prototype.substitute) {
  203. String.prototype.substitute = function(object, regexp){
  204. return this.replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
  205. if (match.charAt(0) == '\\') return match.slice(1);
  206. return (object[name] != undefined) ? object[name] : '';
  207. });
  208. }
  209. }
  210. /*
  211. http://www.JSON.org/json2.js
  212. 2010-03-20
  213. Public Domain.
  214. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  215. See http://www.JSON.org/js.html
  216. This code should be minified before deployment.
  217. See http://javascript.crockford.com/jsmin.html
  218. USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
  219. NOT CONTROL.
  220. This file creates a global JSON object containing two methods: stringify
  221. and parse.
  222. JSON.stringify(value, replacer, space)
  223. value any JavaScript value, usually an object or array.
  224. replacer an optional parameter that determines how object
  225. values are stringified for objects. It can be a
  226. function or an array of strings.
  227. space an optional parameter that specifies the indentation
  228. of nested structures. If it is omitted, the text will
  229. be packed without extra whitespace. If it is a number,
  230. it will specify the number of spaces to indent at each
  231. level. If it is a string (such as '\t' or '&nbsp;'),
  232. it contains the characters used to indent at each level.
  233. This method produces a JSON text from a JavaScript value.
  234. When an object value is found, if the object contains a toJSON
  235. method, its toJSON method will be called and the result will be
  236. stringified. A toJSON method does not serialize: it returns the
  237. value represented by the name/value pair that should be serialized,
  238. or undefined if nothing should be serialized. The toJSON method
  239. will be passed the key associated with the value, and this will be
  240. bound to the value
  241. For example, this would serialize Dates as ISO strings.
  242. Date.prototype.toJSON = function (key) {
  243. function f(n) {
  244. // Format integers to have at least two digits.
  245. return n < 10 ? '0' + n : n;
  246. }
  247. return this.getUTCFullYear() + '-' +
  248. f(this.getUTCMonth() + 1) + '-' +
  249. f(this.getUTCDate()) + 'T' +
  250. f(this.getUTCHours()) + ':' +
  251. f(this.getUTCMinutes()) + ':' +
  252. f(this.getUTCSeconds()) + 'Z';
  253. };
  254. You can provide an optional replacer method. It will be passed the
  255. key and value of each member, with this bound to the containing
  256. object. The value that is returned from your method will be
  257. serialized. If your method returns undefined, then the member will
  258. be excluded from the serialization.
  259. If the replacer parameter is an array of strings, then it will be
  260. used to select the members to be serialized. It filters the results
  261. such that only members with keys listed in the replacer array are
  262. stringified.
  263. Values that do not have JSON representations, such as undefined or
  264. functions, will not be serialized. Such values in objects will be
  265. dropped; in arrays they will be replaced with null. You can use
  266. a replacer function to replace those with JSON values.
  267. JSON.stringify(undefined) returns undefined.
  268. The optional space parameter produces a stringification of the
  269. value that is filled with line breaks and indentation to make it
  270. easier to read.
  271. If the space parameter is a non-empty string, then that string will
  272. be used for indentation. If the space parameter is a number, then
  273. the indentation will be that many spaces.
  274. Example:
  275. text = JSON.stringify(['e', {pluribus: 'unum'}]);
  276. // text is '["e",{"pluribus":"unum"}]'
  277. text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
  278. // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
  279. text = JSON.stringify([new Date()], function (key, value) {
  280. return this[key] instanceof Date ?
  281. 'Date(' + this[key] + ')' : value;
  282. });
  283. // text is '["Date(---current time---)"]'
  284. JSON.parse(text, reviver)
  285. This method parses a JSON text to produce an object or array.
  286. It can throw a SyntaxError exception.
  287. The optional reviver parameter is a function that can filter and
  288. transform the results. It receives each of the keys and values,
  289. and its return value is used instead of the original value.
  290. If it returns what it received, then the structure is not modified.
  291. If it returns undefined then the member is deleted.
  292. Example:
  293. // Parse the text. Values that look like ISO date strings will
  294. // be converted to Date objects.
  295. myData = JSON.parse(text, function (key, value) {
  296. var a;
  297. if (typeof value === 'string') {
  298. a =
  299. /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
  300. if (a) {
  301. return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
  302. +a[5], +a[6]));
  303. }
  304. }
  305. return value;
  306. });
  307. myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
  308. var d;
  309. if (typeof value === 'string' &&
  310. value.slice(0, 5) === 'Date(' &&
  311. value.slice(-1) === ')') {
  312. d = new Date(value.slice(5, -1));
  313. if (d) {
  314. return d;
  315. }
  316. }
  317. return value;
  318. });
  319. This is a reference implementation. You are free to copy, modify, or
  320. redistribute.
  321. */
  322. /*jslint evil: true, strict: false */
  323. /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
  324. call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
  325. getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
  326. lastIndex, length, parse, prototype, push, replace, slice, stringify,
  327. test, toJSON, toString, valueOf
  328. */
  329. // Create a JSON object only if one does not already exist. We create the
  330. // methods in a closure to avoid creating global variables.
  331. if (!this.JSON) {
  332. JSON = {};
  333. }
  334. (function () {
  335. function f(n) {
  336. // Format integers to have at least two digits.
  337. return n < 10 ? '0' + n : n;
  338. }
  339. if (typeof Date.prototype.toJSON !== 'function') {
  340. Date.prototype.toJSON = function (key) {
  341. return isFinite(this.valueOf()) ?
  342. this.getUTCFullYear() + '-' +
  343. f(this.getUTCMonth() + 1) + '-' +
  344. f(this.getUTCDate()) + 'T' +
  345. f(this.getUTCHours()) + ':' +
  346. f(this.getUTCMinutes()) + ':' +
  347. f(this.getUTCSeconds()) + 'Z' : null;
  348. };
  349. String.prototype.toJSON =
  350. Number.prototype.toJSON =
  351. Boolean.prototype.toJSON = function (key) {
  352. return this.valueOf();
  353. };
  354. }
  355. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  356. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  357. gap,
  358. indent,
  359. meta = { // table of character substitutions
  360. '\b': '\\b',
  361. '\t': '\\t',
  362. '\n': '\\n',
  363. '\f': '\\f',
  364. '\r': '\\r',
  365. '"' : '\\"',
  366. '\\': '\\\\'
  367. },
  368. rep;
  369. function quote(string) {
  370. // If the string contains no control characters, no quote characters, and no
  371. // backslash characters, then we can safely slap some quotes around it.
  372. // Otherwise we must also replace the offending characters with safe escape
  373. // sequences.
  374. escapable.lastIndex = 0;
  375. return escapable.test(string) ?
  376. '"' + string.replace(escapable, function (a) {
  377. var c = meta[a];
  378. return typeof c === 'string' ? c :
  379. '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  380. }) + '"' :
  381. '"' + string + '"';
  382. }
  383. function str(key, holder) {
  384. // Produce a string from holder[key].
  385. var i, // The loop counter.
  386. k, // The member key.
  387. v, // The member value.
  388. length,
  389. mind = gap,
  390. partial,
  391. value = holder[key];
  392. // If the value has a toJSON method, call it to obtain a replacement value.
  393. if (value && typeof value === 'object' &&
  394. typeof value.toJSON === 'function') {
  395. value = value.toJSON(key);
  396. }
  397. // If we were called with a replacer function, then call the replacer to
  398. // obtain a replacement value.
  399. if (typeof rep === 'function') {
  400. value = rep.call(holder, key, value);
  401. }
  402. // What happens next depends on the value's type.
  403. switch (typeof value) {
  404. case 'string':
  405. return quote(value);
  406. case 'number':
  407. // JSON numbers must be finite. Encode non-finite numbers as null.
  408. return isFinite(value) ? String(value) : 'null';
  409. case 'boolean':
  410. case 'null':
  411. // If the value is a boolean or null, convert it to a string. Note:
  412. // typeof null does not produce 'null'. The case is included here in
  413. // the remote chance that this gets fixed someday.
  414. return String(value);
  415. // If the type is 'object', we might be dealing with an object or an array or
  416. // null.
  417. case 'object':
  418. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  419. // so watch out for that case.
  420. if (!value) {
  421. return 'null';
  422. }
  423. // Make an array to hold the partial results of stringifying this object value.
  424. gap += indent;
  425. partial = [];
  426. // Is the value an array?
  427. if (Object.prototype.toString.apply(value) === '[object Array]') {
  428. // The value is an array. Stringify every element. Use null as a placeholder
  429. // for non-JSON values.
  430. length = value.length;
  431. for (i = 0; i < length; i += 1) {
  432. partial[i] = str(i, value) || 'null';
  433. }
  434. // Join all of the elements together, separated with commas, and wrap them in
  435. // brackets.
  436. v = partial.length === 0 ? '[]' :
  437. gap ? '[\n' + gap +
  438. partial.join(',\n' + gap) + '\n' +
  439. mind + ']' :
  440. '[' + partial.join(',') + ']';
  441. gap = mind;
  442. return v;
  443. }
  444. // If the replacer is an array, use it to select the members to be stringified.
  445. if (rep && typeof rep === 'object') {
  446. length = rep.length;
  447. for (i = 0; i < length; i += 1) {
  448. k = rep[i];
  449. if (typeof k === 'string') {
  450. v = str(k, value);
  451. if (v) {
  452. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  453. }
  454. }
  455. }
  456. } else {
  457. // Otherwise, iterate through all of the keys in the object.
  458. for (k in value) {
  459. if (Object.hasOwnProperty.call(value, k)) {
  460. v = str(k, value);
  461. if (v) {
  462. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  463. }
  464. }
  465. }
  466. }
  467. // Join all of the member texts together, separated with commas,
  468. // and wrap them in braces.
  469. v = partial.length === 0 ? '{}' :
  470. gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
  471. mind + '}' : '{' + partial.join(',') + '}';
  472. gap = mind;
  473. return v;
  474. }
  475. }
  476. // If the JSON object does not yet have a stringify method, give it one.
  477. if (typeof JSON.stringify !== 'function') {
  478. JSON.stringify = function (value, replacer, space) {
  479. // The stringify method takes a value and an optional replacer, and an optional
  480. // space parameter, and returns a JSON text. The replacer can be a function
  481. // that can replace values, or an array of strings that will select the keys.
  482. // A default replacer method can be provided. Use of the space parameter can
  483. // produce text that is more easily readable.
  484. var i;
  485. gap = '';
  486. indent = '';
  487. // If the space parameter is a number, make an indent string containing that
  488. // many spaces.
  489. if (typeof space === 'number') {
  490. for (i = 0; i < space; i += 1) {
  491. indent += ' ';
  492. }
  493. // If the space parameter is a string, it will be used as the indent string.
  494. } else if (typeof space === 'string') {
  495. indent = space;
  496. }
  497. // If there is a replacer, it must be a function or an array.
  498. // Otherwise, throw an error.
  499. rep = replacer;
  500. if (replacer && typeof replacer !== 'function' &&
  501. (typeof replacer !== 'object' ||
  502. typeof replacer.length !== 'number')) {
  503. throw new Error('JSON.stringify');
  504. }
  505. // Make a fake root object containing our value under the key of ''.
  506. // Return the result of stringifying the value.
  507. return str('', {'': value});
  508. };
  509. }
  510. // If the JSON object does not yet have a parse method, give it one.
  511. if (typeof JSON.parse !== 'function') {
  512. JSON.parse = function (text, reviver) {
  513. // The parse method takes a text and an optional reviver function, and returns
  514. // a JavaScript value if the text is a valid JSON text.
  515. var j;
  516. function walk(holder, key) {
  517. // The walk method is used to recursively walk the resulting structure so
  518. // that modifications can be made.
  519. var k, v, value = holder[key];
  520. if (value && typeof value === 'object') {
  521. for (k in value) {
  522. if (Object.hasOwnProperty.call(value, k)) {
  523. v = walk(value, k);
  524. if (v !== undefined) {
  525. value[k] = v;
  526. } else {
  527. delete value[k];
  528. }
  529. }
  530. }
  531. }
  532. return reviver.call(holder, key, value);
  533. }
  534. // Parsing happens in four stages. In the first stage, we replace certain
  535. // Unicode characters with escape sequences. JavaScript handles many characters
  536. // incorrectly, either silently deleting them, or treating them as line endings.
  537. text = String(text);
  538. cx.lastIndex = 0;
  539. if (cx.test(text)) {
  540. text = text.replace(cx, function (a) {
  541. return '\\u' +
  542. ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  543. });
  544. }
  545. // In the second stage, we run the text against regular expressions that look
  546. // for non-JSON patterns. We are especially concerned with '()' and 'new'
  547. // because they can cause invocation, and '=' because it can cause mutation.
  548. // But just to be safe, we want to reject all unexpected forms.
  549. // We split the second stage into 4 regexp operations in order to work around
  550. // crippling inefficiencies in IE's and Safari's regexp engines. First we
  551. // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
  552. // replace all simple value tokens with ']' characters. Third, we delete all
  553. // open brackets that follow a colon or comma or that begin the text. Finally,
  554. // we look to see that the remaining characters are only whitespace or ']' or
  555. // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
  556. if (/^[\],:{}\s]*$/.
  557. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
  558. replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
  559. replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  560. // In the third stage we use the eval function to compile the text into a
  561. // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
  562. // in JavaScript: it can begin a block or an object literal. We wrap the text
  563. // in parens to eliminate the ambiguity.
  564. j = eval('(' + text + ')');
  565. // In the optional fourth stage, we recursively walk the new structure, passing
  566. // each name/value pair to a reviver function for possible transformation.
  567. return typeof reviver === 'function' ?
  568. walk({'': j}, '') : j;
  569. }
  570. // If the text is not JSON parseable, then a SyntaxError is thrown.
  571. throw new SyntaxError('JSON.parse');
  572. };
  573. }
  574. }());
  575. (function(){
  576. function __sanitize(value) {
  577. return value.sanitize(
  578. ['&', '<', '>', '\'', '"'],
  579. ['&amp;','&lt;','&gt;', '&apos;','&quot;']
  580. );
  581. };
  582. function __toXML(o, t) {
  583. var xml = [];
  584. switch( typeof o ) {
  585. case "object":
  586. if(Object.prototype.toString.apply(o) === '[object Array]') {
  587. var a = o;
  588. if(a.length === 0) {
  589. xml.push("<{tag}/>".substitute({"tag":t}));
  590. } else {
  591. for(var i = 0, len = a.length; i < len; i++) {
  592. xml.push(__toXML(a[i], t));
  593. }
  594. }
  595. } else {
  596. xml.push("<{tag}".substitute({"tag":t}));
  597. var childs = [];
  598. for(var p in o) {
  599. if(o.hasOwnProperty(p)) {
  600. if(p.charAt(0) === "@") xml.push(" {param}='{content}'".substitute({"param":p.substr(1), "content":__sanitize(o[p].toString())}));
  601. else childs.push(p);
  602. }
  603. }
  604. if(childs.length === 0) {
  605. xml.push("/>");
  606. } else {
  607. xml.push(">");
  608. for(var i = 0, len = childs.length; i < len; i++) {
  609. if(p === "#text") { xml.push(__sanitize(o[childs[i]])); }
  610. else if(p === "#cdata") { xml.push("<![CDATA[{code}]]>".substitute({"code": o[childs[i]].toString()})); }
  611. else if(p.charAt(0) !== "@") { xml.push(__toXML(o[childs[i]], childs[i])); }
  612. }
  613. xml.push("</{tag}>".substitute({"tag":t}));
  614. }
  615. }
  616. break;
  617. default:
  618. var s = o.toString();
  619. if(s.length === 0) {
  620. xml.push("<{tag}/>".substitute({"tag":t}));
  621. } else {
  622. xml.push("<{tag}>{value}</{tag}>".substitute({"tag":t, "value":__sanitize(s)}));
  623. }
  624. }
  625. return xml.join('');
  626. }
  627. if (typeof JSON.toXML !== 'function') {
  628. JSON.toXML = function(json, container){
  629. //container = container || "";
  630. var xml = [];
  631. if(container) xml.push("<{tag}>".substitute({"tag":container}));
  632. for(var p in json) {
  633. if(json.hasOwnProperty(p)) {
  634. xml.push(__toXML(json[p], p));
  635. }
  636. }
  637. if(container) xml.push("</{tag}>".substitute({"tag":container}));
  638. return xml.join('');
  639. }
  640. }
  641. })();
  642. </script>