日期:2014-05-16  浏览次数:20532 次

javascript 将对象转换为JSON对象

var userName;
var age;
// Person对象
var Person = function(userName, age) {
	this.userName = userName;
	this.age = age;
}
// 数组
var personArrays = new Array();
var p1 = new Person("DT", 22);
var p2 = new Person("Jacky", 26);
var p3 = new Person("Lily", 21);
personArrays.push(p1);
personArrays.push(p2);
personArrays.push(p3);
// 将array里面所有的Json对象转成字符串
function f_evalArray(obj) {
	var arrays = obj;
	for (var i = 0;i < arrays.length; i++) {
		if (typeof arrays[i] == "object") {
			arrays[i] = obj2str(arrays[i]);
		}
	}
	return "[" + arrays + "]";
}

// json对象转字符串
function obj2str(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 + ":" + obj2str(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(obj2str(o[i]))
			r = "[" + r.join() + "]"
		}
		return r;
	}
	return o.toString();
}
// 将对象转换为为JSON对象
var OString = function(O) {
	var S = [];
	for (var i in O) {
		O[i] = typeof O[i] == "string" ? O[i] : (typeof O[i] == "object"
				? OString(O[i])
				: O[i]);
		S.push("'" + i + "':'" + O[i] + "'");
	}
	return '{' + S.join(',') + '}';
}
console.info(f_evalArray(personArrays));
// 结果:[{userName:"DT",age:22},{userName:"Jacky",age:26},{userName:"Lily",age:21}]
?