JSON字符与JSON对象的相互转换

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<len; i++) {
					strArr.push(jsonToString(obj[i]));
				}
				return '[' + strArr.join(',') + ']';
			} else if(obj==null) {
				return 'null';
			} else {
				var string = [];
				for (var property in obj) string.push(jsonToString(property) + ':' + jsonToString(obj[property]));
				return '{' + string.join(',') + '}';
			}
		case 'number':
			return obj;
		case false:
			return obj;
	}
} 
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();
}

下载文件

posted @ 2011-08-03 14:57  科学家会武术  阅读(257)  评论(0编辑  收藏  举报