JSON Basics Tutorial | Understanding JSON

Source: Internet
Author: User

One

When sending and receiving information in an asynchronous application, you can choose to use plain text and XML as the data format. This issue discusses a useful data format for JavaScript object Notation (JSON), and how to use it more easily to move data and objects in your application.
If you read the previous articles in this series, you should have a good understanding of the format of the data. The previous article explains how to properly use plain text and simple name/value pairs in many asynchronous applications. You can combine the data into the following form:

Firstname=brett&lastname=mclaughlin&[email protected]

That's it, there's no need to do anything anymore. In fact, the WEB veteran will realize that the information sent through a GET request is in this format.
The XML is then discussed in this series. Obviously, XML has received considerable attention (both positive and negative) and has been widely used in Ajax applications. For information about how to use XML data formats, you can review the previous articles in this series:

<request>
<firstName>Brett</firstName>
<lastName>McLaughlin</lastName>
<email>[email protected]</email>
</request>

The data here is the same as seen earlier, but this time in XML format. It's nothing great; this is just another data format that allows us to use XML instead of plain text and name/value pairs.
This article discusses another data format, JavaScript Object Notation (JSON). JSON looks both familiar and unfamiliar. It offers another option, and it's always good to choose a larger range.
Add JSON
When you use name/value pairs or XML, you are actually using JavaScript to get data from your application and convert the data to another data format. In these cases, JavaScript is largely used as a data manipulation language for moving and manipulating data from Web forms and converting the data into a format suitable for sending to server-side programs.
However, sometimes JavaScript is not just used as a format language. In these cases, you are actually using objects in the JavaScript language to represent the data, not just putting the data from the Web form into the request. In these cases, extracting data from JavaScript objects and then putting the data into name/value pairs or XML is a bit superfluous. It is appropriate to use Json:json to allow easy conversion of JavaScript objects to data that can be sent with the request (either synchronously or asynchronously).
JSON is not some kind of magic bullet, but it is a good choice for some very special situations.

Second, the JSON Foundation

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 (see a couple of examples later), but JavaScript is easy to explain, and JSON can represent a more complex structure than name/value pairs. For example, you can represent arrays and complex objects, not just simple lists of keys and values.
Simple JSON Example
In the simplest form, you can represent name/value pairs using JSON such as the following:

1) data stored in name/value pairs
2) data is separated by commas
3) Save the object with curly braces
4) square brackets to save the array

{"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": "[email protected]"}

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.
Array of values
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": "[email protected]"},
{"FirstName": "Jason", "LastName": "Hunter", "email": "[email protected]"},
{"FirstName": "Elliotte", "LastName": "Harold", "email": "[email protected]"}
]}

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": "[email protected]"},
{"FirstName": "Jason", "LastName": "Hunter", "email": "[email protected]"},
{"FirstName": "Elliotte", "LastName": "Harold", "email": "[email protected]"}
],
"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.

Using JSON in JavaScript
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": "[email  Protected] "},
{" FirstName ":" Jason "," LastName ":" Hunter "," email ":" [email protected] "},
{" FirstName ":" Elliotte "," LastName ":" Harold "," email ":" [email protected] "}
],
" authors ": [
{" FirstName ":" Isaac "," LastName ":" Asimov "," Genre ":" Science Fiction "},
{" FirstName ":" Tad "," LastName ":" Williams "," Genre ":" Fantasy "},< br>{"FirstName": "Frank", "LastName": "Peretti", "Genre": "Christian Fiction"}
],
"musicians": [
{"FirstName ":" Eric "," LastName ":" Clapton "," instrument ":" Guitar "},
{" FirstName ":" Sergei "," LastName ":" Rachmaninoff "," Inst Rument ":" 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.

This series has spent a lot of time discussing data formats, mainly because almost all asynchronous applications eventually process data. If you have the tools and techniques to send and receive all types of data and use them in the way that best fits each type of data, you can be more proficient in Ajax. By mastering XML and plain text, you can master the JSON so that more complex data structures are processed in JavaScript.
The next article in this series discusses issues beyond sending data, and provides an in-depth look at how server-side programs receive and process data in JSON format. Also discuss how server-side programs send back data in JSON format across scripts and server-side components, so that XML, plain text, and JSON requests and responses can be blended together. This provides a great flexibility to use all of these tools in almost any combination.

The syntax for XML:

<contact>

<friend>
<name>Michael</name>
<email>[email protected]</email>
</friend>

<friend>
<name>John</name>
<email>[email protected]</email>
</friend>

<friend>
<name>Peggy</name>
<email>[email protected]</email>
</friend>

</contact>

and JSON:

[
{
Name: "Michael",
Email: "[email protected]",
Homepage: "Http://joke.3eyes.org"
},
{
Name: "John",
Email: "[email protected]",
Homepage: "Http://aidapei.3eyes.org"
},
{
Name: "Peggy",
Email: "[email protected]",
Homepage: "Http://www.3eyes.org"
}
]

Format of JSON:
1, object:

{Name: "Peggy", email: "[email protected]", homepage: "Http://www.3eyes.org"}

{property: Value, Property: Value, property: Value}
2, the array is a collection of sequential values. An array starts at "[", Ends with "]", and the values are separated by ",".

[
{Name: "Peggy", email: "[email protected]", homepage: "Http://www.3eyes.org"}, {name: "Peggy", email: "[email protected]" , homepage: "Http://q.3eyes.org"},
{Name: "Peggy", email: "[email protected]", homepage: "Http://zuowen.3eyes.org"}
]

3, the value can be a string, a number, true, false, NULL, or it can be an object or an array. These structures can be nested.

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.