Serialization of JSON and JS objects

Source: Internet
Author: User
Tags javascript array

JavaScript Object Notation (JavaScript object Notation, or JSON) is a lightweight data interchange format that is based on the JS literal notation and is a subset of JS. Although it is a subset of JS but he has nothing to do with language, it can be used to exchange data between applications written in all programming languages now. is a text format that is easier to read and write.

JSON is an unordered collection of "name/value" pairs, which can be any string, and the value can make any JSON-type value. Most programming languages have data types that are mapped to JSON, such as objects (object), dictionaries (dictionary), hash tables (hash maps), associative arrays (associative array), and so on.

JS has six types of values: objects, arrays, strings, numbers, Boolean values, and special values null.
Console.log (Json.parse (' 5 '));//5Console.log (Json.parse (5));//5Console.log (Json.parse (' true '));//trueConsole.log (Json.parse (true));//trueConsole.log (Json.parse (' "Hello"));//"Hello"Console.log (Json.parse ("Hello"));//error Because Hello is not a JSON stringConsole.log (Json.parse (' null '));//NULLConsole.log (Json.parse (NULL));//NULLConsole.log (json.parse (undefined));//error because JSON cannot represent undefined swap null instead
The JSON structure JSON has two structures: the object, the array object structure begins with the "{" Brace, and the "}" brace ends. The middle part consists of 0 or more "key (key)/value (value)" pairs that are separated by ",", and the keyword string and value are separated by ":", and the syntax is structured as code.
{    key1:value1,    key2:value2,    ...}

For example:

{    "name": "Hum",    "age": +,    "sex": 1,    "Love": [        "Swing",        "Jump    ", "Birthday": "1988-01-12"}

Note:

It is best to add single quotes outside the JSON string in JS.

As follows:

Console.log (Json.parse (' {"num": 5, "Stop": true, "str": "Hello", "empty": null} ')); // object{num:5,stop:true,str: "Hello", empty:null}

The JSON object does not have a variable declaration or a semicolon at the end compared to the JS object literal.

The array structure ends with "[" Start, "]". The middle consists of 0 or more lists of values separated by ",", grammatical structures such as code.

[   {       key1:value1,       key2:value2,      ...   }]

For example:

[    {       "Id": 7,      "Mentions": [         {           "Id": 5,           "Statusid": 34,           "createdDateTime": "\/date (1310051914617+0100) \",           "Text": "Text",           "UserName": "UserName",          "Userlocation": "UK",          "Userlanguage": "EN-GB",           "Ischeckin": "True"         }      ],       "Checkins": 0,       "Herenow": 0,       "TimeStamp": "\/date (1310051914639+0100) \",       "Venue": {         "Id": 7,         "Foursquareid": "Cacbf3bd-f0aa-403d-9f9b-2056b4985ba1",         "Name": "Venue name"       }     },   {       "Name": "Hahahhahah",       "Port":[         {             "Port": 8080,             "Protocol": "HTTP",             "IP": "123.12.06.456"         }         ]   }   ]

The JSON array takes the form of a JavaScript array literal.

JSON parsing and serialization of JSON parsing and serialization are the same as AS3. What we commonly use is the JSON object (added in ECMAScript 5, the early JSON parsing basically uses the eval () function of JavaScript. But Eval has some performance and security drawbacks, ECMAScript parsing JSON objects, defining global object JSON, supported browsers with standard browsers and ie8+. For unsupported browsers, the Json2.js file can be introduced. The two methods of Stringify and parse. Let's go on to one by one instructions. JSON.stringifyJSON.stringify () Serializes a JavaScript object into a JSON-formatted string json.stringify (ob,filter,indent) contains three parameters, Usually we use only the first parameter to return a string. OB: An object, an array, the original value to be converted to a JSON string. Filter: is an optional parameter, usually a function, used to replace the value before the string. It can also be an array that contains the property names that need to be serialized. is used for filtering. Indent: is also an optional parameter that uses the indent parameter to specify the string or space to indent when you need to output formatted, readable code. If this argument is omitted, the returned string will not have any extra spaces, so the output value is difficult to read. is used for formatting. Here are a couple of examples: the first is when the second parameter is an array filter:
var ojson = {name: ' Hum ', age:20, sex:1};console.log (json.stringify (Ojson, [///  {"Age": 2 0, "Sex": 1}
If the second argument is a string, the array will be used as the object's property name, and any object whose property name is not in the array will be ignored when serializing. In addition, the order of the properties in the returned string is consistent with the name of the property in the array. Function Filter:
varOjson = {name: ' Hum ', age:26, Sex:1, love: [' swing ', ' jump ']}; Console.log (Json.stringify (Ojson,function(k, v) {Switch(k) { Case' Age ':                returnV > 20? ' Adult ': ' Underage ';  Case' Love ':                returnV.join (', ');  Case' Sex ':                returnundefined; default :                returnv; }    })); //{"name": "Hum", "Age": "Adult", "Love": "Swing,jump"}

If the argument is a function, it is a replacement function that is called on every object that needs to be serialized. The first parameter of this function is the name of the property in the object or the ordinal of the array, and the second is the value itself. The return value of the function replaces the value that needs to be serialized, and if the function returns undefined or does not have any return value, the value is ignored when the string is serialized.

An instance of the third parameter of the stringify:

var ojson = {name: ' Hum ', age:26, Sex:1, love: [' swing ', ' Jump ']};     null, 4));     /*      {         "name": "Hum",         "age": +,         "sex": 1,         "Love": [             "Swing",             "Jump"         ]     }    */
Usually the return value of this method is a machine-readable string without any spaces or line breaks, and if you want to output a more readable code, you need to set a third parameter. Let's look at one more example:
var ojson = {name: ' Hum ', age:26, Sex:1, love: [' swing ', ' Jump ']};     null, '--'));     /*      {     --"name": "Hum",     --"age": +,     --"sex": 1,     --"Love": [     ----"Swing",     ----" Jump "     --]     }     * /

So it's easy to understand ...

JSON.parseJSON.parse used to parse a JSON-formatted string (return an object, array, or original value) Json.parse (s,reviver) Contains two methods. S: the string to parse Reviver: used to convert parse-worthy optional functions we typically use only the first parameter, the optional parameter reviver, which is filtered or post-processed before returning the resolved value. The Reviver function is called once for each original value that is parsed from S. The Reviver function is called with two arguments, the first property name (the object's property name, or the array ordinal that is converted to a string), and the second argument is the object's property or the element value of the array. The Reviver function is invoked as a method that contains the original value of the object/array. The return value of the Reviver function becomes the new value of the property, and if Reviver returns the second argument, the property is unchanged. If Reviver returns undefined or any value, the property is removed from the object or array. Here is an example:
varOjson = {name: ' Hum ', age:26, Sex:1, love: [' swing ', ' jump '], Birthday: ' 1988-01-12 '}; varSjson =json.stringify (Ojson); Console.log (Sjson);//{"name": "Hum", "age": +, "sex": 1, "Love": ["Swing", "Jump"], "Birthday": "1988-01-12"}Console.log (Json.parse (Sjson)); Console.log (Json.parse (Sjson,function(k, v) {if(k = = ' birthday ') {//return Date Object            return NewDate (v); }Else if(k = = ' sex ') {//sex's gone.            returnundefined; }Else{            returnv; }    }));

Serialization of JSON and JS objects

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.