JavaScript 对象转换JSON字符串

JavaScript 对象转换JSON字符串

在项目开发中需要把一些存储数据的对象通过字符串post给后台.
json.org上提供了标准的解决方案:
json2.js中提供了JSON.stringify方法,官方是这么定义的:

JSON.stringify(value, replacer, space)
value 转换对象,通常情况下是对象或是数组

replacer [可选]转换过程的特殊处理,可以是函数或字符串数组

space [可选]设置缩进符

使用示例:

//Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
 
text = JSON.stringify(['e', {pluribus: 'unum'}], null, 't');
// text is '[nt"e",nt{ntt"pluribus": "unum"nt}n]'
 
text = JSON.stringify([new Date()], function (key, value) {
     return this[key] instanceof Date ?'Date(' + this[key] + ')' : value;
});
 // text is '["Date(---current time---)"]'

另外我自己也写了一个方法.
可以满足简单的json对象转换成字符串的需求.
不支持function类转换

//将简单的对象转为字符串
var getJsonString=function(jsonObj){
	//递归解析器
	var loopParse=function(obj,temp){
		//解析数组
		if(obj instanceof Array){
			temp.push("[");
			for(var i=0,j=obj.length;i<j;i++){
				var objNode=obj[i];
				if(typeof objNode=="object"){
					loopParse(objNode,temp);
				}else{
					if(typeof objNode=="string"){
						temp.push("'"+objNode+"',");
					}else{
						temp.push(objNode+",");
					}
				}
			}
			temp.push("],");
		}else if(typeof obj=="object"){ //解析对象
			temp.push("{");
			for(var n in obj){
				if(obj.hasOwnProperty(n)&&n!="prototype"){
					var objNode=obj[n];
					objName=n;
					if(typeof objNode=="object"){
						temp.push("'"+n+"':");
						loopParse(objNode,temp);
					}else{
						if(typeof objNode=="string"){
							temp.push("'"+n+"':'"+objNode+"',");
						}else{
							temp.push("'"+n+"':"+objNode+",");
						}
					}
				}
			}
			temp.push("},");
		}
		return temp.join("").replace(/,(?=[]}])/g,"").slice(0,-1);
	}
	var tempAry=[];
	return loopParse(jsonObj,tempAry);
}
 
getJsonString({name:"zen"}); //"{'name':'zen'}"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值