json转String与String转json及判断对象类型示例代码
程序员文章站
2022-05-25 21:45:56
复制代码 代码如下: function ajaxgetmenulist(){ $.getjson("login.do", function(json){ var r = "...
复制代码 代码如下:
function ajaxgetmenulist(){
$.getjson("login.do", function(json){
var r = "";
znodes += "[";
$(json.menulist).each(function(i){
r = json.menulist[i];
if(i>0) znodes += ",";
znodes += '{';
znodes += 'id:'+r.sid;
znodes += ', pid:'+r.spid;
znodes += ', name:"'+r.stitle;
if(r.spid == 0) znodes += '", open:true';
else znodes += '"';
znodes += '}';
})
znodes += "]";
znodes = stringtojson(znodes);
createtree(znodes);
});
}
/**
* json转string
* @param {object} obj
* @memberof {typename}
* @return {typename}
*/
function jsontostring (obj){
var this = this;
switch(typeof(obj)){
case 'string':
return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
case 'array':
return '[' + obj.map(this.jsontostring).join(',') + ']';
case 'object':
if(obj instanceof array){
var strarr = [];
var len = obj.length;
for(var i=0; i<len; i++){
strarr.push(this.jsontostring(obj[i]));
}
return '[' + strarr.join(',') + ']';
}else if(obj==null){
return 'null';
}else{
var string = [];
for (var property in obj) string.push(this.jsontostring(property) + ':' + this.jsontostring(obj[property]));
return '{' + string.join(',') + '}';
}
case 'number':
return obj;
case false:
return obj;
}
}
/**
* string转json
* @param {object} obj
* @return {typename}
*/
function stringtojson(obj){
return eval('(' + obj + ')');
}
//判断对象类型
function gettype(x){
if(x==null){
return "null";
}
var t= typeof x;
if(t!="object"){
return t;
}
var c=object.prototype.tostring.apply(x);
c=c.substring(8,c.length-1);
if(c!="object"){
return c;
}
if(x.constructor==object){
return c
}
if("classname" in x.prototype.constructor
&& typeof x.prototype.constructor.classname=="string"){
return x.constructor.prototype.classname;
}
return "<unknown type>";
}
上一篇: PHP实现的杨辉三角求解算法分析
下一篇: 编程爱好者学习心得补充