Using JSON data in JavaScript _javascript tips

Source: Internet
Author: User
Tags string to json

JSON is the native format of JavaScript, which means that processing JSON data in JavaScript does not require any special APIs or toolkits.

JSON syntax

JSON is constructed in two structures:

Object-A collection of name/value pairs. In different languages, it is understood as objects, records, structures, dictionaries, hash tables, a list of keys (keyed list), or associative arrays. An object begins with "{" (opening parenthesis), and "}" (closing parenthesis) ends. Each "name" is followed by a ":" (a colon), and the ' name/value ' pair is separated by a ', ' (comma).

Array-an ordered list of values. In most languages, it is understood as an array. An array begins with "[" (left bracket), and "]" (right bracket) ends. Values are separated by the "," (comma) value.

JSON has no variables or other control structures. JSON is used only for data transfer.

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 the data in the people variable, moves to the entry called programmers, moves to the first record ([0]), and finally accesses the value of the LastName 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 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 JSON-formatted object, you can modify the data in the variable like this.

NOTE: JSON-formatted objects and JSON literals are different

var obj={name: "John", "Sex": ' Male '}; JSON-formatted object
var str= "{Name:" John "," Sex ": ' Men '} '; JSON-formatted string (text in JSON format)

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:

var 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 an object named MyObject, you only need to perform the same form of command:

<script type= "Text/javascript" >
function Car (make,model,year,color)
{
this.make=make; 
This.model=model; 
This.year=year; 
This.color=color;
} 
function Showcar ()
{
var carr = new Car ("Dodge", "Coronet R/t", 1968, "Yellow"); 
Alert (carr.tojsonstring ()); 
}
</script>

This is the biggest difference between JSON and other data formats. 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, rather than 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 a server-side program in the request (Ajax).

Method of converting a JSON string to a JSON object

To use the above str1, you must first convert to a JSON object by using the following method:

Converted from JSON string to JSON object
var obj = eval (' + str + ') ');

Or

var obj = Str.parsejson (); Convert from JSON string to JSON object

Or

var obj = json.parse (str); Convert from JSON string to JSON object

Then, you can read this:

Alert (obj.name);
Alert (Obj.sex);

Special Note: If obj is a JSON object, then using the eval () function to convert (even multiple conversions) is a JSON object, but there is a problem with using the Parsejson () function (throwing a syntax exception).

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.