JavaScript json与string互相转换

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>

<head>
<meta http-equiv=”content-type” content=”text/html; charset=iso-8859-1″ />
<meta name=”author” content=”Kisra Wong” />

<title>无标题 2</title>
<script>
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();
}
}
}
;

function a(){
var j = {
a : “abc”
}
;
document.body.innerHTML = j;
document.body.innerHTML += J.JsonToStr( j );
}
</script>

</head>

<body onload=”a();”>

</body>
</htm>

标签