Learning notes for understanding JSON Data Format

Source: Internet
Author: User
Tags closing tag

JSON data format is a lightweight data storage format that is faster than xml for real-time interaction. Below I will give you some pieces of my understanding about JSON data format, I hope this tutorial will be helpful to you.

1. What is JSON

JSON is a lightweight data format based on a subset of javascript syntax, that is, array and object representation. Because javascript syntax is used, JSON definitions can be included in javascript files, and access to them does not need to be parsed in XML-based languages. However, before using JSON, it is very important to understand the special Syntax of arrays and object literally in javascript.


The Json specification is very simple. It can be clearly stated in just a few hundred words on a page, and Douglas Crockford claims that this specification will never need to be upgraded, because it is stipulated in this provision.

1) Separate the parallel data with commas.

2) The ing is represented by a colon.

3) The set (array) of the parallel data is represented by square brackets.

4) The ing set (object) is represented by braces.


1.1 array literal

Array literal, which is a set of javascript values separated by commas (,) enclosed by square brackets. For example:

The Code is as follows: Copy code

Var aNames = ["hello", 12, true, null];

1.2 object literal

The object literal is defined by two curly braces. You can place any number of "name-value" pairs in curly brackets to define the lattice string value ". Except the last line, each "name-value" pair must be followed by a comma (which is similar to the definition of the Union array in Perl ). For example:

The Code is as follows: Copy code

Var oCar = {

"Color": "red ",

"Doors": 4,

"PaidFor": true

};

1.3 mixed literal

We can mix objects and array literal values to create an array of objects or an object containing arrays. For example:

The Code is as follows: Copy code

{Comments :[
{
Id: 1,
Author: "someone1 ",
Url: "http://www.bKjia. c0m ",
Content: "hello"
},
{
Id: 2,
Author: "someone2 ",
Url: "http://www.bKjia. c0m ",
Content: "hello"
},
{
Id: 3,
Author: "someone3 ",
Url: "http://www.bKjia. c0m ",
Content: "hello"
}
]};

1.4 JSON syntax

In Ajax applications, the server directly generates javascript statements. After the client obtains the object, the eval method is used to obtain the object, saving the performance loss of parsing XML. At the same time, the advantage of using JSON as the data format in javascript communication is that you can immediately obtain the data value, so you can access the data contained in it faster.

Var oCarInfo = eval ("(" + sJSON + ")");

Remember: curly braces in javascript are also a statement. The only way for the parser to know that the curly braces represent an object rather than a statement is to find the parentheses that encapsulate it (it is used to indicate that the code is an expression rather than statement ).

1.5 JSON encoding and decoding

As part of the JSON resource, Corockford developed a tool that can directly decode and encode JSON and Javascript objects. The source program of this tool can be downloaded from www.crockford.com/JSON/json.js.

As mentioned above, eval () is used to evaluate any Javascript code passed in, not just JSON. Therefore, when enterprise-level web application development is involved, it has great security risks. To solve this problem, you can use the JSON. parse () method, a parser that only converts JSON code to Javascript. For example:

The Code is as follows: Copy code
Var oObject = JSON. parse (sJSON );

At the same time, it also provides a tool to convert Javascript objects into JSON strings (used during data transmission) (this feature is not supported in Javascript ). All you need to do is pass the object to the JSON. Stringify () method. See the following example:

The Code is as follows: Copy code

Var oCar = new Object ();

OCar. doors = 4;

OCar. color = "blue ";

OCar. year = 1995;

OCar. drivers = new Array ("Penny", "Dan", "Kris ");

Document. write (JSON. stringify (oCar ));

This code will output the following JSON string:

The Code is as follows: Copy code

{"Doors": 4, "color": "blue", "year": 1995, "drivers": ["Penny", "Dan", "Kris"]}

2. JSON and XML

As mentioned above, JSON is simpler than XML.

See XML data to indicate instances:

In XML format:

The Code is as follows: Copy code

<Comments>
<Comment>
<Id> 1 </id>
<Author> someone1 </author>
<Url> http://someone1.x2design.net </url>
<Content> hello </content>
</Comment>
<Comment>
<Id> 2 </id>
<Author> someone2 </author>
<Url> http://someone2.x2design.net </url>
<Content> someone1 </content>
</Comment>
<Comment>
<Id> 3 </id>
<Author> someone3 </author>
<Url> http://someone3.x2design.net </url>
<Content> hello </content>
</Comment>
</Comments>


JSON format:

The Code is as follows: Copy code

{Comments :[
{
Id: 1,
Author: "someone1 ",
Url: "http://someone1.x2design.net ",
Content: "hello"
},
{
Id: 2,
Author: "someone2 ",
Url: "http://someone2.x2design.net ",
Content: "hello"
},
{
Id: 3,
Author: "someone3 ",
Url: "http://someone3.x2design.net ",
Content: "hello"
}
]};


It is easy to find that many redundant information is missing. Because there is no need for a closing tag that matches the opening tag, the number of bytes required to transmit the same information is greatly reduced. Corockford, founder, calls it "XML weight loss solutions ").

Compared with XML, SON-formatted data has a disadvantage that it is less readable for outsiders. Of course, there is a point of view that the data exchange format is not observed by the naked eye. If a tool is used to create and parse the data transmitted back and forth, it is true that there is no reason to require data to be easy to read. The essence of the problem is that there are available JSON tools.


Advantages and disadvantages of JSON

JSON not only reduces the performance and compatibility issues caused by parsing XML parsing, but also is very easy to use for javascript. It is convenient to retrieve data by traversing arrays and accessing object attributes, its readability is good, and it basically has the nature of structured data. I have to say that it is a good method. In fact, google maps does not use XML to transmit data, but uses the JSON scheme.

Another advantage of JSON is cross-origin feasibility. For example, it is completely feasible for you to use it on www.xxx.com, which means you can transmit information across domains. However, XMLHttpRequest cannot obtain cross-origin information, which is restricted by the security nature of javascript.

JSON looks pretty, can it completely replace XML? This is not the case because of the advantages of XML: versatility. It is not easy to make the server generate the javascript code with the correct syntax. This mainly happens in a large system, with different developers on the server and the client. They must negotiate the format of the object, which can easily cause errors.

Example of json Data Format

Example 1

The Code is as follows: Copy code

// Json instance
Var str = '{"firstName": "Bret", "lastName": "McLaughlin "}';
Var j = eval ('+ str + ')');
// For (var key in j) {alert (j [key]);} // traverse the read name
// For (var key in j) {alert (j [key]);} // traverses the read value
// Alert (j. firstName); // read the value of the specified name

Var data = '[{k: "name 1", v: "10 in total"}, {k: "name 2", v: ""}]';
Var json = eval ('+ data +'); // convert to a json object
// Alert (json. length); // output the number of root sub-objects
// If (json [1]. v. length> 1) {alert (dataObj [1]. v );}
// Alert (json [1]. k); // read the value of the specified name
// For (I = 0; I <json. length; I ++) {alert (json. v)} // traverse
// For (var key in json) {alert (json [key]. v);} // traverse
// Var arr = new Array ();
// For (var key in json) {arr. push (json [key]. k);} // concatenate
// Alert (arr. join ('&'));


Example 2

The Code is as follows: Copy code

<Script type = "text/javascript" src = "json2.js"> </script>
<Script>
// Directly declare the json Data Structure
Var myJSONObject = {"bindings ":[
{"IrcEvent": "PRIVMSG", "method": "newURI", "regex": "^ http ://.*"},
{"IrcEvent": "PRIVMSG", "method": "deleteURI", "regex": "^ delete .*"},
{"IrcEvent": "PRIVMSG", "method": "randomURI", "regex": "^ random .*"}
]
};
// Declare the string to compare the difference between the json text and our normal text
Var normalstring = '[{persons: [{name: "jordan", sex: "m", age: "40" },{ name: "bryant", sex: "m", age: "28" },{ name: "McGrady", sex: "m", age: "27"}] ';
Var jsontext = '[{"persons": [{"name": "jordan", "sex": "m", "age": "40 "}, {"name": "bryant", "sex": "m", "age": "28" },{ "name": "McGrady", "sex ": "m", "age": "27"}] ';

// Call the eval function to convert it to a json object,
Var myE = eval (normalstring );
Document. writeln (myE + '<br> ');
// Convert a json object to a string
Var text = JSON. stringify (myE );
// Compare the converted json text with the declared text
Document. writeln ('converted json text: '+ text +' <br> declared json text '+ jsontext +' <br> declared plain text '+ normalstring +' <br> <br> ');

// JSON resolution is better when security is important. JSON parsing only recognizes JSON text and is more secure. The following calls the json parse function to convert text data to generate a json data structure.
Var myData = JSON. parse (jsontext );

Document. writeln (myData + '<br> ');

// The following operations add, query, modify, and delete a json object

// Declare a json object

Var jsonObj2 = {persons: [{name: "jordan", sex: "m", age: "40" },{ name: "bryant", sex: "m ", age: "28" },{ name: "McGrady", sex: "m", age: "27"}]};

Var persons = jsonObj2.persons;
Var str = "";

Var person = {name: "yaoMing", sex: "m", age: "26 "};
// The following is the json object operation. You can view the operation result by removing the annotation.
// JsonObj2.persons. push (person); // Add a record to the array
// JsonObj2.persons. pop (); // Delete the last entry
// JsonObj2.persons. shift (); // Delete the first entry
JsonObj2.persons. unshift (person); // Add a record at the beginning of the array. Any method suitable for Javascript can be used in the array of JSON objects! So there is another method splice () for crud operations! // Delete
// JsonObj2.persons. splice (); // start position, delete count
// Do not delete the replacement
Var self = {name: "tom", sex: "m", age: "24 "};
Var brother = {name: "Mike", sex: "m", age: "29 "};
JsonObj2.persons. splice (, self, brother, self); // start position, delete count, insert object
// Replace and delete
// JsonObj2.persons. splice (0, 1, self, brother); // start position, delete count, insert object

For (var I = 0; I <persons. length; I ++) {var cur_person = persons [I]; str + = cur_person.name + "'sex is" + cur_person.sex + "and age is" + cur_person.age + "<br> ";}
Document. writeln (str );
// Convert to json text
Var myjsonobj = JSON. stringify (jsonObj2 );
Document. writeln (myjsonobj );
</Script>

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.