JSON Basics Tutorial Recommended _json

Source: Internet
Author: User
Tags data structures

If you have read the previous articles in this series, you should have a good understanding of the data format . 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=brett@newinstance.com

That's all you need to do. In fact, theWeb veteran will realize that the information sent through a GET request is in this format.

Then, this series discusses XML. Obviously,XML has received considerable attention (both positive and negative) and has been widely used in Ajax applications. For information on how to use XML data formats, you can review the Previous articles in this column :

<request>
<firstName>Brett</firstName>
<lastName>McLaughlin</lastName>
<email>brett@newInstance.com</email>
</request>

The data here is the same as what we saw earlier, but this time it was in XML format. It's no big deal; 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 provides another option, and choosing a larger range is always a good thing.

Add JSON

When using name / value pairs or XML , you actually use JavaScript to get data from your application and to convert the data into another data format. In these cases,JavaScript is largely a data manipulation language used to move and manipulate data from Web forms and to convert data into a format suitable for sending to server-side programs.

However, sometimes JavaScript is not only used as a format language. In these cases, you actually use objects in the JavaScript language to represent the data, rather than just putting the data from the Web form into the request. In these cases, It's a bit superfluous to extract data from a JavaScript object and then put the data into name/value pairs or XML. This is the right time to use JSON:JSON allows you to easily convert JavaScript objects into data that can be sent with requests (either synchronously or asynchronously).

JSON is not some kind of magic bullet, but it is a good choice for some very special situations.

JSON Basics

Simply put,JSON Converts a set of data represented in a JavaScript object to a string, which can then be easily passed between functions, or in an asynchronous application, the string from the Web The client is passed to the server-side program. This string looks a little odd (see some 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 with JSON such as the following:

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": "Brett@newInstance.com"}

In terms of syntax, this is not a great advantage compared to name/value pairs, but in this case JSON is easier to use and more readable. For example, it is clear that the above three values are part of the same record; curly braces make these values a bit of a connection.

Array of values

When you need to represent a set of values,JSON not only improves readability, but it 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 pairs you see in previous articles in this series ), you must create a proprietary data format or modify the key name to person1-firstName such a form.

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

{"People": [
{"FirstName": "Brett", "LastName": "McLaughlin", "email": "Brett@newInstance.com"},
{"FirstName": "Jason", "LastName": "Hunter", "email": "Jason@servlets.com"},
{"FirstName": "Elliotte", "LastName": "Harold", "email": "Elharo@macfaq.com"}
]}

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

{"Programmers": [
{"FirstName": "Brett", "LastName": "McLaughlin", "email": "Brett@newInstance.com"},
{"FirstName": "Jason", "LastName": "Hunter", "email": "Jason@servlets.com"},
{"FirstName": "Elliotte", "LastName": "Harold", "email": "Elharo@macfaq.com"}
],
"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. It should also be noted, however, that the actual name /value pairs in the record can be different between the main entries (programmers, authors, and musicians). JSON is completely dynamic, allowing you to change 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 that you represent the data, and you can even represent the same thing in different ways.

using JSON in JavaScript

Once you have the JSON format, It's easy to use it in JavaScript. JSON is the native format of JavaScript, which means that processing 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 it directly to the JSON-formatted data string:

var people =
{"Programmers": [
{"FirstName": "Brett", "LastName": "McLaughlin", "email": "Brett@newInstance.com"},
{"FirstName": "Jason", "LastName": "Hunter", "email": "Jason@servlets.com"},
{"FirstName": "Elliotte", "LastName": "Harold", "email": "Elharo@macfaq.com"}
],
"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 that you saw earlier . But that's not enough, because the way the data is accessed doesn't seem obvious.

accessing data

Although it doesn't look obvious, the long string above is actually just an array, and after you put the array in a JavaScript variable, you can easily access it. In fact, you just use dot notation to represent an array element. 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 people the data in the variable, then moves to the named programmers entry, moves to the first record ( [0] ), and finally, the lastName value of the access key. The result is the string value "McLaughlin".

Here are several examples of using the same variable.

People.authors[1].genre//Value is "fantasy"
People.musicians[3].lastname//Undefined. This is 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 using 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 you can't easily convert an object back to the text format mentioned in this article, all data modifications are not of much value. This conversion is also simple in JavaScript:

String Newjsontext = people.tojsonstring ();

That'll do it! You now get a text string that you can use anywhere, for example, as a request string in an Ajax application.

More importantly, you can convert any JavaScript object to JSON text. It is not possible to handle only variables that were previously assigned with a JSON string. In order to convert a named myObject object, 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, simply 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 raw data and the formatted data. Even if you use an API such as 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 that you can easily convert the data into a format that can be sent to server-side programs in the request.

Conclusion

This series has spent a lot of time discussing data formats, mainly because almost all asynchronous applications end up processing data. If you have all the tools and techniques to send and receive all types of data and use them in the best way for each data type, you'll be more proficient in Ajax. By mastering XML and plain text, and then mastering JSON, you can handle more complex data structures in JavaScript.

The next article in this series will discuss issues other than sending data, and delve into how server-side programs receive and process JSON -formatted data. Also discuss how server-side programs can send back data in JSON format across scripting and server-side components so that XML, plain text, and JSON requests and responses are mixed together. This provides a great flexibility to use all of these tools in combination with almost any combination.

How XML is worded:

<contact>

<friend>

<name>Michael</name>

<email>17bity@gmail.com</email>

</friend>

<friend>

<name>John</name>

<email>john@gmail.com</email>

</friend>

<friend>

<name>Peggy</name>

<email>peggy@gmail.com</email>

</friend>

</contact>

and JSON:

[

{

Name: "Michael",

Email: "17bity@gmail.com",

Homepage: "Http://www.jialing.net"

},

{

Name: "John",

Email: "John@gmail.com",

Homepage: "Http://www.jobn.com"

},

{

Name: "Peggy",

Email: "Peggy@gmail.com",

Homepage: "Http://www.jb51.net"

}

]

JSON the Format :

1, object:

{Name: "Peggy", Email: "Peggy@gmail.com", Homepage: "Http://www.jb51.net"}

{ property: Value, property: Value, property: Value}

2, the array is a collection of sequential values. An array begins with "[", ends with "]", and thevalues are separated by "," .

[

{Name: "Peggy", Email: "Peggy@gmail.com", Homepage: "Http://www.jb51.net"}, {name: "Peggy", Email: "Peggy@gmail.com", Homepage: "Http://www.jb51.net"},

{Name: "Peggy", Email: "Peggy@gmail.com", Homepage: "Http://www.jb51.net"}

]

3, the value can be a string, a number, true, false, null, or 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.