Copy Code code as follows:
/*
Convert a JSON object to a string
How to use:
var json = {id=3,name= "abc"};
var str = tools.j2s (JSON);
*/
Tools.j2s = function (O) {
var S = [];
var J = "";
if (Object.prototype.toString.apply (O) = = ' [Object Array] ') {
for (var i = 0; i < o.length; i++) {
S.push (This.j2s (o[i));
}
J = ' [' + s.join (', '] + '] ';
else if (Object.prototype.toString.apply (O) = = ' [Object Date] ') {
J = "New Date (" + o.gettime () + ")";
else if (Object.prototype.toString.apply (O) = = ' [Object RegExp] ' | | Object.prototype.toString.apply (O) = = ' [object Function] ') {
J = O.tostring ();
else if (Object.prototype.toString.apply (O) = = ' [Object] ') {
for (var i in O) {
var tempobj = "";
if (typeof (O[i]) = = ' String ') {
Tempobj = ' "' + o[i] + '";
else if (typeof (O[i]) = = ' object ') {
Tempobj = This.j2s (O[i]);
} else {
Tempobj = O[i];
}
S.push (' "' + i + '": ' + tempobj ');
}
J = ' {' + s.join (', ') + '} ';
else if (Object.prototype.toString.apply (O) = = ' [Object String] ') {
J = ' "' + O + '";
} else {
J = O;
}
return J;
};
JSON string converted to JSON object
tools.s2j = function (jsonstring) {
if (jsonstring = null | | jsonstring = = "") {
Jsonstring = "{}";
}
Return eval (' (' +jsonstring+ ') ');
};
JSON string to Object
Tools.json2obj = function (_json) {
if (_json = = "") {
Alert ("Function initialization failed!) ");
Return "";
}
Return eval ("({root:" +_json+ "})");
};