Because of work requirements, JSON objects must be converted into strings on the JS end and written to users' cookies to save users' personal operation habits. I searched the internet and found that there were many methods, some codes were not clear and confused, some were not fully considered, and some generated strings were problematic, So I integrated some good writing methods, I made some improvements. You may still have to worry about it, but I feel that you have taken into consideration all the common types. I hope you can give me some advice!
JSON. stringify (jsonobj) is the easiest method, but there are browser compatibility problems (only applicable to IE8 +, Chrome 1 +, FF 3 + ).
Copy to ClipboardReference: [www.bkjia.com] var O2String = function (O ){
// Return JSON. stringify (jsonobj );
Var S = [];
Var J = "";
If (Object. prototype. toString. apply (O) = '[object Array]') {
For (var I = 0; I <O. length; I ++)
S. push (O2String (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 Object]') {
For (var I in O ){
O [I] = typeof (O [I]) = 'string '? '"' + O [I] + '"': (typeof (O [I]) = 'object '? O2String (O [I]): O [I]);
S. push (I + ':' + O [I]);
}
J = '{' + S. join (',') + '}';
}
Return J;
};
/* ----------------------- The following is the test code -----------------------*/
Var jsonStr = O2String (
[
{
"Page": "plan ",
"Custom ":
[
{
"ItemName": "CustomLabel1 ",
"ItemContent": 1,
"IsItem": true,
"ItemDate": new Date (1320774905467 ),
"ItemReg":/[\ w] *? /Gi,
"ItemFunc": function () {alert ("ItemFunc ");}
},
{
"ItemName": "CustomLabel1 ",
"ItemContent": 1,
"IsItem": true,
"ItemDate": new Date (1320774905467 ),
"ItemReg":/[\ w] *? /Gi,
"ItemFunc": function () {alert ("ItemFunc ");}
}
]
},
{
"Page": "project ",
"Custom ":
[
{
"ItemName": "CustomLabel2 ",
"ItemContent": 2,
"IsItem": false,
"ItemDate": new Date (1320774905467 ),
"ItemReg":/[\ w] *? /Gi,
"ItemFunc": function () {alert ("ItemFunc ");}
},
{
"ItemName": "CustomLabel2 ",
"ItemContent": 2,
"IsItem": false,
"ItemDate": new Date (1320774905467 ),
"ItemReg":/[\ w] *? /Gi,
"ItemFunc": function () {alert ("ItemFunc ");}
}
]
}
]
);
Alert (jsonStr );
Var jsonObj = eval ("(" + jsonStr + ")");
Alert (jsonObj. length );
(Source: Blog)