This article mainly introduces the simple implementation case of converting JavaScript objects to json arrays. If you need it, you can refer to it for help.
The Code is as follows:
Function obj2Str (obj ){
Switch (typeof (obj )){
Case 'object ':
Var ret = [];
If (obj instanceof Array ){
For (var I = 0, len = obj. length; I <len; I ++ ){
Ret. push (obj2Str (obj [I]);
}
Return '[' + ret. join (',') + ']';
}
Else if (obj instanceof RegExp ){
Return obj. toString ();
}
Else {
For (var a in obj ){
Ret. push (a + ':' + obj2Str (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" = )? "\ N" :( "\ r" = )? "\ R" :( "\ t" = )? "\ T": "" ;}) + "\"";
Case 'boolean ':
Return obj. toString ();
Default:
Return obj. toString ();
}
}