JSON data Format Understanding learning Notes

Source: Internet
Author: User
Tags closing tag comments data structures eval json

1. What is JSON

The JSON concept is simple, and JSON is a lightweight data format based on a subset of JavaScript syntax, arrays and object representations. Because JavaScript syntax is used, JSON definitions can be included in JavaScript files, and access to them does not need to be parsed in an xml-based language. Before using JSON, however, it is important to understand the special syntax for arrays and object literals in JavaScript.


The specification of JSON is very simple, with only one page of hundreds of words to be clear, and Douglas Crockford claims that this specification never need to upgrade, because the provisions of the rules.

1 The data is separated by commas (",").

2) The mapping is represented by a colon (":").

3 the Set (array) of parallel data is represented by square brackets ("[]").

4 the Mapped collection (object) is represented by braces ("{}").


1.1 Literal amount of the array

The literal amount of an array is a comma-separated set of JavaScript values enclosed in a single pair of parentheses, for example:

The code is as follows Copy Code

var anames=["Hello", A, true, NULL];

1.2 Object literal

The object literal is defined by two curly braces. You can place any number of "name-value" pairs within the curly braces to define the format string values. In addition to the last line, each name-value pair must have a comma (this is similar to the definition of a federated array in Perl). For example:

The code is as follows Copy Code

var Ocar = {

"Color": "Red",

"Doors": 4,

' Paidfor ': true

};

1.3 Mixed literal volume

We can mix objects and arrays literally to create an array of objects, or an object that contains an array. For example:

The code is as follows Copy Code

{comments:[
{
Id:1,
Author: "Someone1",
URL: "Http://www.111cn.net",
Content: "Hello"
},
{
Id:2,
Author: "Someone2",
URL: "Http://www.111cn.net",
Content: "Hello"
},
{
Id:3,
Author: "Someone3",
URL: "Http://www.111cn.net",
Content: "Hello"
}
]};

1.4 JSON Syntax

In AJAX applications, the server generates JavaScript statements directly, and the client acquires the object directly using the Eval method, which eliminates the ability to parse XML. Also, the advantage of using JSON as a data format in JavaScript communication is that you can get the value of the data immediately, so you can access the data it contains more quickly.

var ocarinfo = eval ("+ Sjson +"));

Keep in mind that curly braces are also a statement in JavaScript. The only way for the parser to know that the curly braces represent an object, not a statement, is to find the parentheses that encapsulate it (it's used to indicate that the code is an expression, not a statement).

1.5 JSON encoding and decoding

As part of the JSON resource, Corockford developed a tool that enables direct decoding and encoding of JSON and JavaScript objects. The source program for this tool can be downloaded in www.crockford.com/JSON/json.js.

There are some inherent drawbacks to using eval () on the above: it is used to evaluate any incoming Javascript code, not just JSON. Therefore, when it comes to enterprise-level Web application development, it has a lot of security implications. To solve this problem, you can use the parser Json.parse () method that is used only to convert the JSON code to Javascript. For example:

The code is as follows Copy Code
var oobject = Json.parse (Sjson);

It also provides a tool for converting JavaScript objects to JSON strings (which are used in data transfer) (not built in JavaScript to support this feature). All you have to do is pass the object to JSON. Stringify () method. Take a look at 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 JSON string shown below:

The code is as follows Copy Code

{"Doors": 4, "Color": "Blue", "Year": 1995, "Drivers": ["Penny", "Dan", "Kris"]}

2. JSON and XML

As mentioned above, one of the great advantages of JSON versus XML is that it's simpler.

See XML Data Representation instance:

Using XML to represent:

  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>


Use JSON to represent:

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's easy to see that a lot of redundant information is missing. Because there is no need to have an end tag (closing tag) that matches the start tag (opening tag), the number of bytes required to transfer the same information is greatly reduced. Founder Corockford called it the "XML Weight-loss program".

The disadvantage of SON format data compared to XML is that it is less readable for laymen. There is, of course, a view that data interchange formats are not visually observable. If you create and parse data that is transmitted back and forth through tools, there is no reason to require that data be easy to read. The essence of the problem is that there are available JSON tools.


JSON Advantages and Disadvantages

Not only does JSON reduce the performance and compatibility problems of parsing XML parsing, but it's easy to use for JavaScript, it's easy to get data by traversing arrays and accessing object properties, and it's also good for readability, with the basic properties of structured data. Have to say is a good way, and in fact, Google Maps did not use XML to pass data, but the use of JSON scheme.

Another advantage of JSON is cross-domain feasibility, such as your use on www.xxx.com Web pages, which means you can pass information across domains. Using XMLHttpRequest does not capture cross-domain information, which is restricted by the security nature of JavaScript.

JSON looks beautiful, does it completely replace XML? This is not true, and the reason is the advantages of XML: versatility. It is not easy to produce syntactically qualified JavaScript code on the server side, which occurs primarily in a larger system, with different developers on the server side and the client. They must negotiate the format of the object, which can easily cause errors.

JSON data Format instance

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]);}//Traversal read name
for (var key in J) {alert (J[key]);} Traversal Read value
alert (j.firstname); Read the value of the specified name

var data= ' [{k: "Name 1", V: "Total 10"},{k: "Name 2", V: ""}] ';
var json=eval (' (' +data+ ') ');//Convert to JSON object
Alert (json.length)//output The number of child objects of root
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)}//traversal
for (Var key in JSON) {alert (JSON[KEY].V);} Traverse
var arr = new Array ();
for (Var key in JSON) {Arr.push (JSON[KEY].K);} Stitching
Alert (Arr.join (' & '));


Example 2

The code is as follows Copy Code

<script type= "Text/javascript" src= "Json2.js" ></script>
<script>
Declaring JSON data structures directly
var myjsonobject = {"Bindings": [
{"Ircevent": "Privmsg", "Method": "Newuri", "regex": "^http://.*"},
{"Ircevent": "Privmsg", "Method": "Deleteuri", "regex": "^delete.*"},
{"Ircevent": "Privmsg", "Method": "Randomuri", "regex": "^random.*"}
]
};
Declare a string to compare the difference between JSON text and our normal text
var normalstring= ' [{persons:[{name: "Jordan", Sex: "M", Age: "{"}, {name: "Bryant", Sex: "M", Age: "A"}, {name: "McGrady", Sex: "M", Age: "27"}]}] ';
var jsontext= ' [{persons ']: [{' Name ': ' Jordan ', ' sex ': ' m ', ' Age ': '} ', {' name ': ' Bryant ', ' sex ': ' m ', ' Age ': ' '}, {' Name ":" McGrady "," Sex ":" M "," Age ":" 27 "}]}] ';

Call the Eval function into a JSON object,
var Mye = eval (normalstring);
Document.writeln (mye+ ' <br><br> ');
Convert a JSON object to a string
var text = json.stringify (Mye);
Compare the converted JSON text to the declared text difference
Document.writeln (' converted JSON text: ' +text+ ' <br><br> declared JSON-formatted text ' +jsontext+ ' <br><br> declared plain text ' +normalstring+ ' <br><br> ');

It's better to use JSON parsing when security is more important. JSON parsing only recognizes JSON text and it is more secure, and the following call JSON's parse function generates a JSON data structure for text conversion
var myData = Json.parse (Jsontext);

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

The following is a check on the JSON object's additions and deletions

Declaring a JSON object

var jsonobj2={persons:[{name: "Jordan", Sex: "M", Age: "N"}, {name: "Bryant", Sex: "M", Age: "A"}, {name: "McGrady", Sex: "M ", Age:" 27 "}]};

var persons=jsonobj2.persons;
var str= "";

var person={name: "Yaoming", Sex: "M", Age: "26"};
The following is the operation of the JSON object, which removes the annotation to view the results of the operation
JsonObj2.persons.push (person);//array last add a record
JsonObj2.persons.pop ()//Delete last item
JsonObj2.persons.shift ();//Delete first item
JsonObj2.persons.unshift (person);//array front plus a record as long as the appropriate JavaScript method can be used in the JSON object array! So there is another way to splice () CRUD Operations! Delete
JsonObj2.persons.splice (0,2)//start position, delete number
Replace do not delete
var self={name: "Tom", Sex: "M", Age: "24"};
var brother={name: "Mike", Sex: "M", Age: "29"};
JsonObj2.persons.splice (1,0,self,brother,self);//start position, delete number, insert Object
Replace and delete
JsonObj2.persons.splice (0,1,self,brother);//start position, delete number, insert Object

for (Var i=0;i<persons.length;i++) {var cur_person=persons[i]; str+=cur_person.name+ "' Sex are ' +cur_person.sex+" and Age is "+cur_person.age+" <br><br>; }
Document.writeln (str);
Convert to JSON text
var myjsonobj = json.stringify (JSONOBJ2);
Document.writeln (Myjsonobj);
</script>

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.