Detailed explanation of Json parsing by jQuery _ jquery

Source: Internet
Author: User
Tags tojson
This article mainly introduces jQuery's method for parsing Json, and analyzes common parsing and conversion techniques of jQuery for json in detail based on the example form. It has some reference value, for more information about how jQuery parses Json, see the following example. We will share this with you for your reference. The details are as follows:

Preface

In the WEB data transmission process, json is transmitted in the lightweight form of text, that is, strings. The client generally uses JS to operate on the received JSON object. Therefore, mutual conversion between JSON objects and JSON strings and parsing of JSON data are the key.

First, clarify two concepts, for example:

JSON string:

The Code is as follows:

var str1 = '{ "name": "deyuyi", "sex": "man" }';

JSON object:

The Code is as follows:

var str2 = { "name": "deluyi", "sex": "man" };

It can be understood as follows:

JSON objects can be directly formatted using JQuery operations. For example, in C #, objects (class names) can be used to point out attributes (methods;

The JSON string is only a string and is a whole. If it is not intercepted, the data stored in it cannot be taken out and used directly, unless you only want alert;

1. convert a JSON string to a JSON object

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

A: eval function

The eval function can directly convert strings in JSON format that conform to the essence or are similar to JSON format into JSON objects. The usage is as follows:

Eval ('+ str +'); // Where str is the string that meets the description in this Title


// Convert the JSON string to the JSON object var str = '{"name": "John"}'; var obj = eval ('+ str + ')'); alert (obj. name); var str2 = "{'name': 'john'}"; var obj2 = eval ('+ str2 +'); alert (obj2.name ); var str3 = "{name: 'john'}"; var obj3 = eval ('+ str3 +'); alert (obj3.name );


The preceding output result is john ".

The Eval mode can convert the following standard and non-standard format strings:


var str="{ 'name': 'John' }";var str2='{ "name": "John" }';var str3="{ name: 'John' }";


See JqueryDemo1.html in this example.

B: parseJSON Function

Another function that converts a standard string to a JSON object is parseJSON (). For example, jQuery. parseJSON (str) // Where str is the string that meets the requirements described in this title.


// Convert the JSON string to the JSON object var str = '{"name": "John"}'; var obj = jQuery. parseJSON (str) alert ("1" + obj. name );


The preceding output result is john ".

This method only supports the standard format: var str = '{"name": "John "}';

See JqueryDemo2.html in this example.

C: JSON. parse function

Another function that converts a standard string to a JSON object is JSON. parse (). For example, JSON. parse (str) // Where str is the string that meets the requirements described in this title.


var str = '{ "name": "mady", "age": "24" }';var obj = JSON.parse(str);alert(obj.name);


The preceding output result is john ".

This method only supports the standard format: var str = '{"name": "John "}';

See JqueryDemo3.html in this example.

The above results are consistent and all output names, such:

NOTE: If obj is a JSON object, it is still a JSON object after eval () function conversion (even Multiple conversions), but parseJSON () is used () A problem occurs after the function is processed (a syntax exception is thrown ).

D: Other Method

If you can't help making mistakes, you really want to parse non-standard and informal strings, such:

The Code is as follows:

{name:mady,age:23}

Or

The Code is as follows:

{name:'mady',age:23}

And other illegal formats that you can think of are essentially correct, so there are extended libraries to solve

Jquery-json extension Library

Here: http://code.google.com/p/jquery-json/

This library is used to extend jQuery. For JSON usage, two functions are extended: toJSON and parseJSON.

The toJSON function is used to serialize a common JavaScript Object into a JSON object.
The parseJSON function is used to serialize a common JavaScript Object into a JSON object too.


var data=$.toJSON({ x: 2, y: 3 }); var obj = jQuery.parseJSON(data); alert(obj.x); var str = {plugin: 'jquery-json', version: 2.3}; var data2=$.toJSON(str); var obj2 = jQuery.parseJSON(data2); alert(obj2.plugin);


The preceding code execution result is as follows:

See JqueryDemo5.html in this example.

2. convert a JSON object to a string

You can use toJSONString () or the global method JSON. stringify () to convert a JSON object to a JSON string.
For example:

The Code is as follows:

Var last = obj. toJSONString (); // converts a JSON object to a JSON character

Or


Var last = JSON. stringify (obj); // converts a JSON object to the JSON character alert (last );


Iii. parse and read JSON

We can parse the string into a JSON object in various ways.
For example:

The Code is as follows:

var str2 = { "name": "mady", "sex": "man" };

You can read it as follows:

The Code is as follows:

Alert (str2.name); // same as C #, direct to the outbound vertex...

"Mady" is displayed ".
JSON is rarely as simple as this. For example, JSON objects with a little complexity are as follows:

The Code is as follows:

var str={"GetUserPostByIdResult":{"Age":"33","ID":"2server","Name":"mady"}};

Resolution:

Alert (str. GetUserPostByIdResult. Name); // I cannot click it at a time.

A little more complex, such:

The Code is as follows:

var data=" { root: [ {'name':'6200','value':'0'}, {'name':'6101','value':'xa'}, {'name':'6102','value':'beijing'}, {'name':'6103','value':'haerbin'}]}";


If you want to make a single choice, use:

The Code is as follows:

alert(dataObj.root[0].name);

"6200" is displayed ".

If you want to select a group, use:


$.each(dataObj.root, function(index, item) {  $("#info").append(      "" +index+":"+ item.name + "" +       "" +index+":"+ item.value + "");});


Here, "# info" is the ID of a DIV. The input result is as follows:

See JqueryDemo4.html in this example.

Note: For example, if you want to use other conversion functions, change the single quotation marks in the string to double quotation marks and the external quotation marks to single quotation marks.
Click here to download the complete instance code in this article.

The above is the details of jQuery's Json parsing instance _ jquery. For more information, please follow the PHP Chinese Network (www.php1.cn )!

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.