Use of JSON in JS

Source: Internet
Author: User

The main advantage of JSON is that the format is streamlined, compared to XML. Generally used as data transmission, the front and back end of the transmission.

Now popular browsers generally support two methods of JSON, serialization and deserialization.

1. Json.stringnify ()

2. Json.parse ()

The following example is a common use of these two methods.

Note that the two methods of JSON ignore undefined's project properties, such as the item with key test is ignored.

varA;varperson = {    "FullName": "Mr Xi",    "Wife": "Miss Peng",    "Children": ["Xi1", "Xi2"],    "Age": 53,    "Test": A};console.log (a); //undefinedvarstr = json.stringify (person);//typically serialized, can be uploaded to the backgroundConsole.log (str);//{"FullName": "Mr Xi", "Wife": "Miss Peng", "Children": ["Xi1", "Xi2"], "age":varJobj = Json.parse (str);//after uploading to the foreground from the backstage, the analysisConsole.log (Jobj);

Most of the time, most of us neglect the second parameter of these two methods. The second parameter is primarily used for filtering (either an array, or a function).

When an array is passed, the keys for the JSON object are passed, and the property is included, otherwise filtered out.

When a function, the function has two parameters are key and value, for their own business processing, return undefined is not included, otherwise return value.

varSTR1 = json.stringify (person, ["FullName", "children"]); Console.log (str1);//{"FullName": "Mr Xi", "Children": ["Xi1", "Xi2"]}varstr2 = json.stringify (person,function(k,v) {if(k = = "Children")) {V.push ("Xi3"); returnv; } Else if(k = = "Age"){        returnundefined; } Else {        returnv; }}); Console.log (str2) ;//{"FullName": "Mr Xi", "Wife": "Miss Peng", "Children": ["Xi1", "Xi2", "Xi3"]}

 

  

Use of JSON in JS

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.