1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
/*
Script: Json.js
Simple Json parser and Stringyfier, See: <http://www.json.org/>
License:
MIT-style license.
*/
/*
Class: Json
Simple Json parser and Stringyfier, See: <http://www.json.org/>
*/
var Json =
/*
Property: toString
Converts an object to a string. For example to be passed in server-side scripts as a parameter.
Only converts from $type boolean, number, string, array and object.
Arguments:
obj - the object to convert to string
Returns:
A json string or null, if the object is not encodable.
Example:
(start code)
Json.toString({apple: 'red', lemon: 'yellow'}); '{"apple":"red","lemon":"yellow"}'
(end)
*/
switch$typeobj
case 'boolean':
return Stringobj;
case 'string':
return '"' + objreplaceJsonregExpfunctionchr
return JsonspecialCharschr || '\\u00' + MathfloorchrcharCodeAt / 16toString16 + chrcharCodeAt % 16toString16;
+ '"';
case 'array':
return '[' + objmapJsontoStringremovenulljoin',' + ']';
case 'object':
var string = ;
forvar prop in obj
var val = JsontoStringobjprop;
ifval stringpushJsontoStringprop + ':' + val;
return '{' + stringjoin',' + '}';
case 'number':
if isFiniteobj return Stringobj;
// fall through
case false:
return 'null';
return null;
regExp: /([\x00-\x1f\\"])/g
specialChars: '\b': '\\b''\t': '\\t''\n': '\\n''\f': '\\f''\r': '\\r''"' : '\\"''\\': '\\\\'
/*
Property: evaluate
converts a json string to an javascript Object.
Arguments:
str - the string to evaluate. If its not a string, it returns null.
secure - optionally, performs syntax check on json string. Defaults to false.
Credits:
Json test regexp is by Douglas Crockford <http://crockford.org>.
Example:
>var myObject = Json.evaluate('{"apple":"red","lemon":"yellow"}');
>//myObject will become {apple: 'red', lemon: 'yellow'}
*/
if $typestring != 'string' || !stringlength return null;
if secure && !/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/teststringreplace/\\./g'@'replace/"[^"\\\n\r]*"/g'' return null;
return eval'(' + string + ')';
;
|
Pastie
