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'}"