JSON字符转对象
var stringToJson = function(data) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim(data); // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if (/^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") .replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse(data) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); }}
JSON对象转字符
var jsonToString = function(obj) { switch(typeof(obj)){ case 'string': return '"' + obj.replace(/(["\\])/g, '\\$1') + '"'; case 'array': return '[' + obj.map(jsonToString).join(',') + ']'; case 'object': if(obj instanceof Array) { var strArr = []; var len = obj.length; for(var i=0; i
JSON对象转字符
function arrayToJson(o) { var r = []; if(typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\""; if(typeof o == "object") { if(!o.sort) { for (var i in o) { r.push(i + ":" + arrayToJson(o[i])); if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) { r.push("toString:" + o.toString.toString()); } } r = "{" + r.join() + "}"; } else { for (var i = 0; i < o.length; i++) { r.push(arrayToJson(o[i])); } r = "[" + r.join() + "]"; } return r; } return o.toString();}