Json对象转普通字符串
<script>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 == "function") continue;
json.push(
i.toJSON() + " : " +
((this != null) ? this.toJSON() : "null")
)
}
return "{\n " + json.join(",\n ") + "\n}";
}
Array.prototype.toJSON = function()
{
for (var i = 0, json = []; i < this.length; i++)
json = (this != null) ? this.toJSON() : "null";
return "[" + json.join(", ") + "]"
}
String.prototype.toJSON = function()
{
return '"' +
this.replace(/(\\|\")/g, "\\$1")
.replace(/\n|\r|\t/g, function()
{
var a = arguments;
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;
(c >= ' ') ?
(c == '\\') ? (tmp = '\\\\') :
(c == '"') ? (tmp = '\\"') : 0 :
(tmp =
(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 a = { a: "aaa", b: "bbb", c: 123 };
var s = a.toJSON();
alert(s);
//-------------------------------------------
</script>
在网上看到一个很经典的类:
<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=o,s.self=o)};})(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;
if(oo instanceof Array){
sA.push(i+':[');
for(var b in oo){
if(oo.hasOwnProperty(b) && b!='prototype'){
sA.push(oo+',');
if(typeof oo=='object') arguments.callee(oo);
}
}
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(/\,/ig,'').replace(/,\}/g,'}').replace(/,\]/g,']').slice(0,-1);
},
push:function(sName,sValue){
this.self = sValue;
this = 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;
if(oo instanceof Array){
sA.push(i+':[');
for(var b in oo){
if(oo.hasOwnProperty(b) && b!='prototype'){
sA.push(oo+',');//感觉此处似乎没有必要加上,因为有这句所有最后需要replace(/\,/ig,'')
if(typeof oo=='object') arguments.callee(oo);
}
}
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(/\,/ig,'').replace(/,\}/g,'}').replace(/,\]/g,']').slice(0,-1);
}
这经过验证是有效的,无论是复杂的还是简单的json对象。push方法里面this.self = sValue;
this = 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);
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));
}
return '[' + ret.join(',') + ']';
}
else if (obj instanceof RegExp)
{
return obj.toString();
}
else
{
for (var a in obj)
{
ret.push(a + ':' + J.JsonToStr(obj));
}
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 == "function") continue;
json.push(
i.toJSON() + " : " +
((this != null) ? this.toJSON() : "null")
)
}
return "{\n " + json.join(",\n ") + "\n}";
}
Array.prototype.toJSON = function(){
for(var i=0,json=[];i<this.length;i++)
json = (this != null) ? this.toJSON() : "null";
return "["+json.join(", ")+"]"
}
String.prototype.toJSON = function(){
return '"' +
this.replace(/(\\|\")/g,"\\$1")
.replace(/\n|\r|\t/g,function(){
var a = arguments;
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;
(c >= ' ') ?
(c == '\\') ? (tmp = '\\\\'):
(c == '"') ? (tmp = '\\"' ): 0 :
(tmp =
(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 : ,
func : function(x,y){return x+y},
obj : {a : "b"}
}.toJSON();
alert(json);
// result
{
"str" : "abcde",
"num" : 6,
"reg" : /foobar/i,
"array" : ,
"func" : function(x,y){return x+y},
"obj" : {
"a" : "b"
}
}
页:
[1]