Read JavaScript Advanced Programming 13-json

Source: Internet
Author: User
Tags tojson javascript array

JSON is a lightweight data format that simplifies the effort to represent data structures. In the actual work, we often use it to pass data, but some of the details of its use should be noted. Native JSON objects are defined in ECMAScript5, which can be used to serialize objects into JSON strings or to parse JSON data into JavaScript objects.

First, JSON syntax

JSON can be used to represent three types of values: Simple values, objects, and arrays. Objects and arrays are generally the outermost form of a JSON structure.

1.JSON Simple Value

You can represent strings, numeric values, Booleans, and Null in JSON.

For example:

5// numeric type "Hello json"// String type

Attention:

①json does not support the special value undefined in JS;

②json strings must use double quotes and cannot use single quotes.

③ in practice, JSON is typically used to represent a more complex data structure, whereas simple values are generally used as part of complex data structures.

2. Objects

A JSON object is similar to the syntax of a JavaScript object literal object.

// JavaScript Object literal representation var jsweatherinfo={City  :"Beijing",  Cityid:"101010100",  weather:" Cloudy to clear "//JSON object {  " city ":" Beijing ",  " Cityid ":" 101010100 ",   "Weather": "Cloudy Turn Clear"}

But there are several differences:

There is no concept of variables in ①json, so no variables are declared;

②json no semicolon at the end;

The attribute names in the ③json object must use double quotation marks, and attribute quotes in JavaScript objects are optional.

3. Arrays

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

// JavaScript Arrays var result=[1,true, "Today"]; // JSON Array [1,true, "Today"]

Difference: The JSON array does not have a semicolon at the end, nor does it declare a variable.

Second, JSON serialization

1.JSON objects

The eval () function of JavaScript can be used to parse JSON and return JavaScript objects, but eval () is risky in evaluating the JSON structure. Therefore, a global JSON object is added to the ECMAScript5. The JSON object has two methods: Stringify () and parse ().

Stringify () is used to serialize JavaScript objects into JSON strings;

Parse () parses a JSON string into its native JavaScript value.

var weather={' city ': ' Beijing ',' Cityid ': ' 101010100 ',' temp1 ': ' 31 ℃ ',' Temp2 ': ' 20 ℃ ',' weather ': ' Cloudy to clear ',' img1 ': ' D1.gif ',' img2 ': ' N0.gif ',' ptime ': ' 11:00 ' }; var text=json.stringify (weather); var json=json.parse (text); json.weather; // "Nice and Sunny"

2.json.stringify ()

The Json.stringify () method has three parameters:

The first parameter is a JavaScript object to serialize;

The second parameter is a filter, which can be an array or a function;

The third parameter is a Boolean value that indicates whether indentation is preserved in the JSON string.

① Filter

If the filter parameter is an array, only the attributes listed in the array are included in the stringify () result.

var weather={' city ': ' Beijing ',' Cityid ': ' 101010100 ',' temp1 ': ' 31 ℃ ',' Temp2 ': ' 20 ℃ ',' weather ': ' Cloudy to clear ',' img1 ': ' D1.gif ',' img2 ': ' N0.gif ',' ptime ': ' 11:00 ' }; var text=json.stringify (weather,["City", "Weather", "Temp1", "Temp2"]); // Result: "{" City ":" Beijing "," Weather ":" Cloudy to Clear "," Temp1 ":" 31 ℃ "," Temp2 ":" 20 ℃ "}"

If the filter is a function, the passed-in function has two parameters: the property name and the property value. Determines how the corresponding property in the serialized object is handled, based on the attribute name. If the function returns undefined, the corresponding property is ignored.

varText1 = json.stringify (Weather,function(key, value) {Switch(key) { Case' Temp1 ':return' Maximum temperature ' +value; Case' Temp2 ':return' Minimum temperature ' +value; Case' Img1 ': Case' Img2 ': Case' Ptime ':returnUndefined//property is ignoreddefault:returnvalue;}});//Result: "City": "Beijing", "Cityid": "101010100", "Temp1": "Maximum temperature 31 ℃", "Temp2": "Minimum temperature 20 ℃", "Weather": "Cloudy to Clear"} "

③ String Indentation

Json.stringify () The third parameter is used to control the indentation in the result.

If the indent parameter passes in a numeric value, it represents the number of spaces that each JSON field indents, but the maximum number of indent spaces does not exceed 10.

var text2=json.stringify (weather,null, 5)

If the indent parameter is passed into a string, it means that each level in the JSON string is used as the indent character. However, the string cannot be more than 10 characters long.

var text3=json.stringify (weather,null, "--")

④tojson () method

If Json.stringify () does not meet the serialization requirements of some objects, you can customize the Tojson method for the object to return its own JSON data format.

var weather={' city ': ' Beijing ',' Cityid ': ' 101010100 ',' temp1 ': ' 31 ℃ ',' Temp2 ': ' 20 ℃ ',' weather ': ' Cloudy to clear ',  toJSON:function() {  return this. city+. weather+ ", maximum temperature" + this. temp1+ ", minimum temperature" + this. temp2;  }}; Json.stringify (weather); // " " Beijing cloudy to clear, the maximum temperature of 31 ℃, the lowest temperature of 20 ℃ ""

In these cases, the order of the Json.stringify () serialized objects is as follows:

① The method is called if the object has a Tojson method and can return a valid value, otherwise the serialization is performed in the default order.

② if Stringify () has a second parameter, apply the filter;

③ serializes each value returned by step ②;

④ If there is a third argument, the corresponding formatting is performed.

third, JSON parsing

Json.parse () is used to parse a JSON string into a JavaScript object.

The first parameter of the method to parse the JSON string;

The second parameter is a function restore function. The restore function has two parameters, key and value. If the Restore function returns undefined, the property is removed from the result, and if other values are returned, the value is inserted into the result. A restore function is often used when converting a date string to a data date object.

varJSON = {  ' City ': ' Beijing ',  ' Cityid ': ' 101010100 ',  ' Temp1 ': ' 19 ℃ ',  ' Temp2 ': ' 32 ℃ ',  ' Weather ': ' Sunny ',  ' Ptime ':NewDate ()};varText =json.stringify (JSON); Json.parse (text,function(key, value) {Switch(key) { Case' Ptime ':    return NewDate (value);//return Date Object   Case' Cityid ':    returnUndefined//Delete this property  default:    returnvalue; }});

Read JavaScript Advanced Programming 13-json

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.