Simple Example of converting a common object to an object in json format.

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.