Home  >  Article  >  Web Front-end  >  Using JSON data in JavaScript_javascript tips

Using JSON data in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 15:15:411640browse

JSON is a native JavaScript format, which means that processing JSON data in JavaScript does not require any special API or toolkit.

JSON syntax

JSON is constructed from two structures:

Object - a collection of name/value pairs. In different languages, it is understood as an object, record, structure, dictionary, hash table, keyed list, or associative array. An object starts with "{" (left bracket) and ends with "}" (right bracket). Each "name" is followed by a ":" (colon); "name/value" pairs are separated by a "," (comma).

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

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

Assign JSON data to variables

For example, you can create a new JavaScript variable and assign a JSON-formatted data string directly to it:

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 data in the JSON format we saw earlier. However, this is not enough as the way to access the data does not seem obvious yet.

Access Data

Although it may not seem obvious, the long string above is actually just an array; you can easily access this array by placing it in a JavaScript variable. In fact, just use dot notation to represent array elements. So, to access the last name of the first entry in the programmers list, just use code like this in JavaScript:

people.programmers[0].lastName;

Note that array indexing 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 the string value "McLaughlin" .

Here are a few examples 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"

Using this syntax, you can process any JSON format data without using any additional JavaScript toolkit or API.

Modify JSON data

Just as data can be accessed using periods and brackets, data can be easily modified in the same way:

people.musicians[1].lastName = "Rachmaninov";

After converting the string into a JavaScript json format object, you can modify the data in the variable like this.

Note: json format objects and json text are different

var obj={name:" 张三 ","sex":' 男 '}; //json 格式的对象
var str=" { name: " 张三 " , "sex" : ' 男 ' }" ; //json 格式的字符串( json 格式的文本)

Convert back to string

Of course, all data modifications are of little value if you can't easily convert the object back to the text format mentioned in this article. This conversion is also simple in JavaScript:

var newJSONtext = people.toJSONString();

That’s it! You now have a text string that you can use anywhere, for example, as a request string in an Ajax application.

More importantly, any JavaScript object can be converted to JSON text. It is not only possible to handle variables originally assigned with JSON strings. To convert an object named myObject, just execute a command of the same form:

<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, you only need to call a simple function to get the formatted data, which is ready to use. For other data formats, conversion between raw and formatted data is required. Even when using an API like the Document Object Model (which provides functions for converting your own data structures into text), you need to learn the API and use the API's objects instead of using native JavaScript objects and syntax.

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

Method to convert JSON string to JSON object

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

//由JSON字符串转换为JSON对象
var obj = eval('(' + str + ')');

or

var obj = str.parseJSON(); //由JSON字符串转换为JSON对象

or

var obj = JSON.parse(str); //由JSON字符串转换为JSON对象

Then, you can read it like this:

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

Special note: If obj is originally a JSON object, then it will still be a JSON object after using the eval() function to convert it (even if it is converted multiple times), but there will be problems after using the parseJSON() function to process it (throwing a syntax exception) .

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn