JSON data format

Source: Internet
Author: User

at present, the development of projects between the various languages with the interface is to communicate through the JSON format, in particular, the Web project and mobile phone app and other data communication between the project, all through the JSON format to pass the information, today we talk about the JSON data format syntax and implementation:JSON data format

JSON (JavaScript Object Notation) is a lightweight data interchange format. JSON takes a completely language-independent text format, which makes JSON an ideal data exchange Language. Easy to read and write, but also easy to machine parse and Generate.

Basic structure

JSON is constructed in two structures:

1. Collection of Name/value pairs (A collection of Name/value pairs). In different languages, It is understood as objects (object), recording (record), structure (struct), dictionary (dictionary), hash table (hash table), keyed list (keyed list), or associative array (associative Array).

2. Ordered list of values (an ordered list of values). In most languages, it is understood as an array (array).

Basic example

Simply put, JSON can convert a set of data represented in a JavaScript object into a string, which can then be easily passed between functions, or in an asynchronous application passing a string from a WEB client to a server-side Program. The string looks a bit odd, but JavaScript is easy to explain, and JSON can represent a more complex structure than a name/value pair. For example, you can represent arrays and complex objects, not just simple lists of keys and Values.

Represents a Name/value pair

In the simplest form, a "name/value pair" can be represented by a JSON such as the following:{"firstName": "Brett"}

This example is very basic, and actually takes up more space than the equivalent plain text "name/value pair":Firstname=brett

however, when multiple name/value pairs are strung together, JSON reflects its value. first, You can create records that contain multiple name/value pairs, such as:

{"firstName": "Brett", "lastName": "McLaughlin", "email": "aaaa"}

In terms of syntax, this has no significant advantage over Name/value pairs, But in this case JSON is easier to use and more readable. For example, It makes it clear that the above three values are part of the same record, and that the curly braces make some of these values a Connection.

Represents an array

When you need to represent a set of values, JSON not only improves readability, but also reduces Complexity. For example, Suppose you want to represent a list of people. In XML, many start and end tags are required, and if you use a typical name/value pair (like the name/value pair you see in the previous article in this series), you must create a proprietary data format or change the key name to a form such as Person1-firstname.

If you use JSON, you only need to group multiple records with curly braces Together:

{"people": [

{"firstName": "Brett", "lastName": "McLaughlin", "email": "aaaa"},

{"firstName": "Jason", "lastName": "Hunter", "email": "bbbb"},

{"firstName": "elliotte", "lastName": "Harold", "email": "cccc"}

]}

It's not hard to Understand. In this example, there is only one variable named people, and the value is an array of three entries, each of which is a Person's record with first name, last name, and e-mail address. The above example shows how to combine records into a single value with Parentheses. of course, you can use the same syntax to represent multiple values (each value contains multiple records):

{"programmers": [

{"firstName": "Brett", "lastName": "McLaughlin", "email": "aaaa"},

{"firstName": "Jason", "lastName": "Hunter", "email": "bbbb"},

{"firstName": "elliotte", "lastName": "Harold", "email": "cccc"}

],

"authors": [

{"firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction"},

{"firstName": "Tad", "lastName": "Williams", "genre": "fantasy"},

{"firstName": "Frank", "lastName": "peretti", "genre": "christian fiction"}

],

"musicians": [

{"firstName": "Eric", "lastName": "Clapton", "instrument": "guitar"},

{"firstName": "Sergei", "lastName": "rachmaninoff", "instrument": "piano"}

] }

Most notable here is the ability to represent multiple values, each of which in turn contains multiple Values. however, It should also be noted that the actual name/value pairs in the record can differ between the different main entries (programmers, authors, and musicians). JSON is completely dynamic, allowing changes in the way the data is represented in the middle of the JSON structure.

There are no predefined constraints to follow when working with JSON-formatted Data. so, in the same data structure, you can change the way you represent data, and you can even represent the same thing in different ways.

Format app

Once you've mastered the JSON format, it's easy to use it in JavaScript. JSON is a native JavaScript format, which means that working with JSON data in JavaScript does not require any special APIs or Toolkits.

Assigning JSON data to a variable

For example, You can create a new JavaScript variable, and then assign the JSON-formatted data string directly to It:

var people = {"programmers": [{"firstName": "Brett", "lastName": "McLaughlin", "email": "aaaa"},

{"firstName": "Jason", "lastName": "Hunter", "email": "bbbb"},

{"firstName": "elliotte", "lastName": "Harold", "email": "cccc"}

],

"authors": [

{"firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction"},

{"firstName": "Tad", "lastName": "Williams", "genre": "fantasy"},

{"firstName": "Frank", "lastName": "peretti", "genre": "christian fiction"}

],

"musicians": [

{"firstName": "Eric", "lastName": "Clapton", "instrument": "guitar"},

{"firstName": "Sergei", "lastName": "rachmaninoff", "instrument": "piano"}

] }

This is very simple; now people contains the JSON-formatted data you saw Earlier. however, This is not enough, because the way data is accessed doesn't seem to be obvious.

accessing data

Although it doesn't seem obvious, the long string above is really just an array, and after you put the array into a JavaScript variable, it's easy to Access. In fact, you simply represent the array element with a dot Notation. so, to access the last name of the first entry in the programmers list, just use the following code in JavaScript:

people.programmers[0].lastname;

Note that the array index is Zero-based. so, This line of code first accesses the data in the people variable, then moves to the entry called programmers, then moves to the first record ([0]), and finally accesses the value of the LastName KEY. The result is a string value of "McLaughlin".

Here are a few examples of using the same variable.

People.authors[1].genre//Value is "fantasy"

People.musicians[3].lastname//Undefined. This refers to the fourth entry, and there isn ' t one

People.programmers[2].firstname//Value is "elliotte"

With this syntax, you can work with any JSON-formatted data without the need for any additional JavaScript toolkits or Apis.

modifying JSON data

Just as you can access data with dots and parentheses, you can easily modify the data in the same way:

People.musicians[1].lastname = "rachmaninov";

After you convert a string to a JavaScript object, you can modify the data in the variable like This.

Convert back to String

of course, if the object cannot be easily converted back to the text format mentioned in this article, then all data modifications are not of much Value. This conversion is also simple in JavaScript:

String Newjsontext = people.tojsonstring ();

It's all right! Now you get a text string that can be used anywhere, for example, you can use it as a request string in an Ajax Application.

More importantly, You can convert any JavaScript object to JSON Text. You can not only handle variables that were originally assigned with a JSON string. In order to convert an object named myobject, you only need to perform the same form of command:

String Myobjectinjson = myobject.tojsonstring ();

This is the biggest difference between JSON and other data formats discussed in this Series. If you use JSON, just call a simple function, you can get the formatted data, you can use it directly. For other data formats, you need to convert between the original data and the formatted Data. Even if you use an API such as the Document Object Model (which provides a function to convert your data structure to text), you need to learn the API and use the object of the API instead of using native JavaScript objects and syntax.

The final conclusion is that JSON is almost certainly a good choice if you are dealing with a large number of JavaScript objects, so you can easily convert the data into a format that can be sent to the Server-side program in the Request.

Concept comparison

Comparison of JSON and XML

Readability

JSON and XML are comparable in readability, with simple syntax on one side and a canonical label on the other, which makes it difficult to distinguish between the winners and Losers.

scalability

XML is inherently well-extensible, and json, of course, has nothing to do with XML extension, and JSON does Not. however, json in the JavaScript home combat, can store JavaScript compound object, with XML incomparable Advantage.

Coding Difficulty

XML has a wealth of coding tools, such as dom4j, jdom, and so on, and JSON also provides tools. Without tools, It is believed that skilled developers can quickly write the desired XML document and JSON string, but the XML document has many more characters on the Structure.

decoding Difficulty

There are two ways to parse Xml:

One is to parse through the document model, that is, to index a set of tags through the parent tag. For example: Xmldata.getelementsbytagname ("tagName"), But this is to be used in the case of Pre-knowledge of the document structure, unable to do a generic encapsulation.

Another way is to traverse nodes (document and childNodes). This can be achieved through recursion, but the parsed data is still different form, often can not meet the Pre-requirements.

It must be difficult to parse any such extensible structure Data.

The same is true for Json. If you know the JSON structure in advance, it is wonderful to use JSON for data passing, and you can write very useful, aesthetically readable code. If you are a purely front-desk developer, you will love json very much. But if you're an app developer, it's not like that, after all, XML is the real structured markup language for data transfer.

It's a nightmare to parse JSON without knowing the structure of the Json. Time and effort not to say, the code will become redundant procrastination, the results are also unsatisfactory. however, this does not affect many foreground developers to choose Json. Because toJSONString () in json.js, you can see the string structure of the Json. Of course not using this string, it's still a Nightmare. When people who use JSON see the string, the JSON structure is straightforward and the JSON is easier to Manipulate.

The above is the parsing of XML and JSON only for data passing in Javascript. In javascript, JSON is a home battle, and its advantages are certainly far superior to Xml. If you store JavaScript composite objects in JSON and don't know their structure, I'm sure a lot of programmers are crying and parsing json as Well.

Instance Comparison

Both XML and JSON use structured methods to tag the data, and Here's a simple Comparison.

Some of the provinces and cities of China are represented by XML as Follows:

<?xml version= "1.0" encoding= "utf-8"?>

<country>

<name> China </name>

<province>

<name> Heilongjiang </name>

<cities>

<city> Harbin </city>

<city> Daqing </city>

</cities>

</province>

<province>

<name> Guangdong </name>

<cities>

<city> Guangzhou </city>

<city> Shenzhen </city>

<city> Zhuhai </city>

</cities>

</province>

</country>


This is represented by json:

{

{name: "china", province:[{name: "heilongjiang", cities:{city:["harbin", "daqing"]},

{name: "guangdong", cities:{city:["guangzhou", "shenzhen", "zhuhai"]}

}


I am engaged in software project development 20, 10 Java Engineer series of teaching work, recording more than 30 quality video courses, Each course contains the project actual combat, class ppt, and complete source code download, interested friends can see my online classroom, if want to more detailed comprehensive study ajax+ Jquery+json Data communication technology, You can see my ajax+jquery from getting started to proficient in video courses

JSON data format

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.