Json object
Copy codeThe Code is as follows:
Var json = {aa: true, bb: true };
Var json1 = {aa: 'B', bb: {cc: true, dd: true }};
1: js json object operation
Copy codeThe Code is as follows:
For (var item in json ){
Alert (item); // The result is aa, bb, And the type is string.
Alert (typeof (item ));
Alert (eval ("json." + item); // The result is true, and the true type is boolean.
Eval ("json." + item + "= false;"); // change the value of the json object
}
2: how to convert a json object to a String object
Copy codeThe Code is as follows:
/**
* Convert a json object to a string
*/
Function json2str (o ){
Var arr = [];
Var fmt = function (s ){
If (typeof s = 'object' & s! = Null) return json2str (s );
Return/^ (string | number) $/. test (typeof s )? "'" + S + "'": s;
}
For (var I in o) arr. push ("'" + I + "':" + fmt (o [I]);
Return '{' + arr. join (',') + '}';
}
3: convert a string object to a json object
Copy codeThe Code is as follows:
Function stringToJson (stringValue)
{
Eval ("var theJsonValue =" + stringValue );
Return theJsonValue;
}
4: Method for converting a json array to a String object (to remove the method above)
Copy codeThe Code is as follows:
Function JsonArrayToStringCfz (jsonArray)
Var JsonArrayString = "[";
For (var I = 0; I <jsonArray. length; I ++ ){
JsonArrayString = JsonArrayString + JsonToStringCfz (jsonArray [I]) + ",";
}
JsonArrayString = JsonArrayString. substring (0, JsonArrayString. length-1) + "]";
Return JsonArrayString;
}
5: Use json. js json to convert string
Copy codeThe Code is as follows:
<Script src = "json2.js"> </script>
<Script>
Var date = {myArr: ["a", "B", "c", "d"], count: 4 };
Var str = JSON. stringify (date );
Alert (str );
</Script>