json对象转换成json字符串

var JSON = function(sJSON) {
	this.objType = (typeof sJSON);
	this.self = [];
	(function(s, o) {
		for (var i in o) {
			o.hasOwnProperty(i) && (s[i] = o[i], s.self[i] = o[i])
		};
	})(this, (this.objType == 'string') ? eval('0,' + sJSON) : sJSON);
}
JSON.prototype = {
	toString : function() {
		return this.getString();
	},
	valueOf : function() {
		return this.getString();
	},
	getString : function() {
		var sA = [];
		(function(o) {
			var oo = null;
			sA.push('{');
			for (var i in o) {
				if (o.hasOwnProperty(i) && i != 'prototype') {
					oo = o[i];
					if (oo instanceof Array) {
						sA.push(i + ':[');
						for (var b in oo) {
							if (oo.hasOwnProperty(b) && b != 'prototype') {
								sA.push(oo[b] + ',');
								if (typeof oo[b] == 'object')
									arguments.callee(oo[b]);
							}
						}
						sA.push('],');
						continue;
					} else {
						sA.push(i + ':' + oo + ',');
					}
					if (typeof oo == 'object')
						arguments.callee(oo);
				}
			}
			sA.push('},');
		})(this.self);
		return sA.slice(0).join('').replace(/\[object object\],/ig, '')
				.replace(/,\}/g, '}').replace(/,\]/g, ']').slice(0, -1);
	},
	push : function(sName, sValue) {
		this.self[sName] = sValue;
		this[sName] = sValue;
	}
}


测试:


var strA = '{allPrivList: [{id:"func001", desc:"商品管理"},{id:"func002", desc:"類別管理"},{id:"func003", desc:"行銷管理"}],groupList: [{id:"g001", desc:"客服", privList: ["func001", "func002", "func004"] },{id:"g002", desc:"營運", privList: ["func003"]}]}';
var objA = new JSON(strA);
alert(objA);
alert(objA.allPrivList[0].desc + '\n' + objA.groupList[0].privList + '\n'
		+ objA.groupList[1].desc);
objA.push("C", [1, "hello baby", function() {
					alert(this.C[1])
				}]);
alert(objA);
objA.C[2].call(objA);
var objB = new JSON({});
alert(objB);
objB.push("A", function() {
			alert('test A')
		});
alert(objB);
objB.A();
var objC = new JSON([1]);
alert(objC);
objC.push("A", function() {
			alert('test A')
		});
alert(objC.A);
var xTree = new JSON({
			name : 'root',
			list : [{
						name : '1',
						list : [{
									name : '1-1',
									list : []
								}, {
									name : '1-2',
									list : []
								}]
					}, {
						name : 'look at me',
						list : []
					}]
		});
alert(xTree);
var r = xTree.list.splice(1, 1)[0];
alert(xTree);
xTree.list[0].list.splice(1, 0, r);
alert(xTree);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值