Simple Example of converting a common object to an object in json format.
1. What is JSON?
JSON is only a data format (it is not a new data type)
Var obj = {name: "China", age: 5000}; //-> common format object
Var jsonObj = {"name": "China", "age": 5000 }; //-> object in JSON format (you only need to wrap the attribute name of a Common Object with "" (not ''). This format is an object in JSON format)
Var data = [
{Name: "", age :""},
{Name: "", age :""}
]; //-> A common two-dimensional array
Var jsonData = [
{"Name": "", "age ":""},
{"Name": "", "age ":""}
]; //-> JSON format data
2. Some methods provided for us to operate JSON format data in the window browser object
-> Window. JSON
-> Stringify: converts an object in JSON or common format to a string in JSON format.
-> Parse: converts a JSON string to an object in JSON format.
Var data = [
{Name: "Li Si", age: 48 },
{Name: "Zhang San", age: 84}
];
Var str = JSON. stringify (data); //-> '[{"name": "Li Si", "age": 48 },{ "name": "Zhang San", "age ": 84}]'
Console. log (JSON. parse (str ));
3. compatibility issues
In IE6 and IE7, the window does not have the JSON attribute.
Console. log (window. JSON);-> in IE6 ~ 7. The output result is undefined.
How can I convert a string in JSON format to an object in JSON format when it is incompatible? -> Use eval, but remember to manually add parentheses to the left and right sides of the string.
Var str = '[{"name": "", "age": 48 },{ "name": "Zhang San", "age": 84}]';
Var data = eval ("(" + str + ")"); //-> compatible, we use JSON. parse (str)
Console. dir (data );
The preceding simple example of converting a common object into a json object is all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support for the customer's house.