- 注册时间
- 2010-11-11
- 最后登录
- 2025-5-27
- 阅读权限
- 200
- 积分
- 14361
- 精华
- 2
- 帖子
- 843
  

 TA的每日心情 | 无聊 2025-5-27 03:37:20 |
---|
签到天数: 366 天 [LV.9]以坛为家II
|
在网上看到一个很经典的类:
<script type="text/javascript">
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;
}
}
===========================
可以把里面的转换方法拿出来用:
function getJsonString(jsonObj){
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]+',');//感觉此处似乎没有必要加上,因为有这句所有最后需要replace(/\[object object\],/ig,'')
if(typeof oo[b]=='object') arguments.callee(oo[b]);
}
}
sA.push('],');
continue;
}else{
if(typeof oo=='number')sA.push(i+':'+oo+',');
else sA.push(i+":'"+oo+"',");
}
if(typeof oo=='object') arguments.callee(oo);
}
}
sA.push('},');
})(jsonObj);
return sA.slice(0).join('').replace(/\[object object\],/ig,'').replace(/,\}/g,'}').replace(/,\]/g,']').slice(0,-1);
}
这经过验证是有效的,无论是复杂的还是简单的json对象。push方法里面this.self[sName] = sValue;
this[sName] = sValue;
为什么要做2次,保存了2个对象?红色标记部分是对原js进行的修改,非number类型的还是需要加上引号。这种方法不能处理数组型的json数据,比如:[{},{}]这种形式的,受此启发,下面的方法则可以处理这种情况。
function getJsonString(jsonObj){
var sA = [];
(function(o){
var isObj=true;
if(o instanceof Array)
isObj=false;
else if(typeof o!='object'){
if(typeof o=='string')
sA.push('"'+o+'"');
else
sA.push(o);
return;
}
sA.push(isObj?"{":"[");
for(var i in o){
if(o.hasOwnProperty(i) && i!='prototype'){
if(isObj)
sA.push(i+':');
arguments.callee(o[i]);
sA.push(',');
}
}
sA.push(isObj?"}":"]");
})(jsonObj);
return sA.slice(0).join('').replace(/,\}/g,'}').replace(/,\]/g,']');
}
下面还有一种方法:
var J = {
StrToJSON: function(str) {
var a;
eval('a=' + str + ';');
return a;
},
JsonToStr: function(obj) {
switch(typeof(obj))
{
case 'object':
var ret = [];
if (obj instanceof Array)
{
for (var i = 0, len = obj.length; i < len; i++)
{
ret.push(J.JsonToStr(obj[i]));
}
return '[' + ret.join(',') + ']';
}
else if (obj instanceof RegExp)
{
return obj.toString();
}
else
{
for (var a in obj)
{
ret.push(a + ':' + J.JsonToStr(obj[a]));
}
return '{' + ret.join(',') + '}';
}
case 'function':
return 'function() {}';
case 'number':
return obj.toString();
case 'string':
return "\"" + obj.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g, function(a) {return ("\n"==a)?"\\n":("\r"==a)?"\\r":("\t"==a)?"\\t":"";}) + "\"";
case 'boolean':
return obj.toString();
default:
return obj.toString();
}
}
};
比如:
jsonObj = J.StrToJSON(jsonStr);
这个没有进行验证,用到了正则。
=============再一种,未验证========
代码:
Object.prototype.deep_clone = function(){
eval("var tmp = " + this.toJSON());
return tmp;
}
Object.prototype.toJSON = function(){
var json = [];
for(var i in this){
if(!this.hasOwnProperty(i)) continue;
//if(typeof this[i] == "function") continue;
json.push(
i.toJSON() + " : " +
((this[i] != null) ? this[i].toJSON() : "null")
)
}
return "{\n " + json.join(",\n ") + "\n}";
}
Array.prototype.toJSON = function(){
for(var i=0,json=[];i<this.length;i++)
json[i] = (this[i] != null) ? this[i].toJSON() : "null";
return "["+json.join(", ")+"]"
}
String.prototype.toJSON = function(){
return '"' +
this.replace(/(\\|\")/g,"\\$1")
.replace(/\n|\r|\t/g,function(){
var a = arguments[0];
return (a == '\n') ? '\\n':
(a == '\r') ? '\\r':
(a == '\t') ? '\\t': ""
}) +
'"'
}
Boolean.prototype.toJSON = function(){return this}
Function.prototype.toJSON = function(){return this}
Number.prototype.toJSON = function(){return this}
RegExp.prototype.toJSON = function(){return this}
// strict but slow
String.prototype.toJSON = function(){
var tmp = this.split("");
for(var i=0;i<tmp.length;i++){
var c = tmp[i];
(c >= ' ') ?
(c == '\\') ? (tmp[i] = '\\\\'):
(c == '"') ? (tmp[i] = '\\"' ): 0 :
(tmp[i] =
(c == '\n') ? '\\n' :
(c == '\r') ? '\\r' :
(c == '\t') ? '\\t' :
(c == '\b') ? '\\b' :
(c == '\f') ? '\\f' :
(c = c.charCodeAt(),('\\u00' + ((c>15)?1:0)+(c%16)))
)
}
return '"' + tmp.join("") + '"';
}
测试:
var json = {
str : "abcde",
num : 6,
reg : /foobar/i,
array : [1,2,3,4,5],
func : function(x,y){return x+y},
obj : {a : "b"}
}.toJSON();
alert(json);
// result
{
"str" : "abcde",
"num" : 6,
"reg" : /foobar/i,
"array" : [1, 2, 3, 4, 5],
"func" : function(x,y){return x+y},
"obj" : {
"a" : "b"
}
} |
|