How jquery parses data in json format (Object and string) _ jquery

Source: Internet
Author: User
This article describes how jquery parses json data, including the parsing techniques for json objects and json strings, and provides a complete json data parsing example using jQuery, it has some reference value. If you need it, you can refer to the following example to describe how jquery parses json format data. We will share this with you for your reference. The details are as follows:

Json data is a common small real-time data exchange. It can be parsed using jquery or js. Next I will introduce jquery's json string parsing method.

I. jQuery parses Json data format:

To use this method, you must set parameters in the Ajax request:

DataType: "json"

Obtain the data returned by the callback function and parse it to get the desired value. See the source code:

jQuery.ajax({ url: full_url, dataType: "json", success: function(results) { alert(result.name); } });

Normally, you can return JSON data from the background, and the foreground will be handed over to jQuery. Haha !!

Jquery asynchronous requests set the type (usually this Configuration Attribute) to "json", or use $. the getJSON () method does not need the eval () method to obtain the server response, because the result is already a json object. You only need to call this object directly. Here, $. the getJSON method is used as an example.

Example 1

The Code is as follows:

Var data = "{root: [{name: '1', value: '0'}, {name: '000000', value: 'beijing'}, {name: '20140901', value: 'tianjin City '}, {name: '20160301', value: 'shanghai'}, {name: '20160301', value: 'chongqing '}, {name: '000000', value: 'weinan City '}, {name: '000000', value: 'yan'an City'}, {name: '000000', value: 'hanzhong City '}, {name: '000000', value: 'yulin City'}, {name: '000000', value: 'ankang City '}, {name: '200', value: 'shangluo City '}]} ";

Jquery

$. GetJSON ("http://www.jb51.net/", {param: "sanic"}, function (data) {// The data returned here is already a json object // The following other operations are the same as the first case $. each (data. root, function (idx, item) {if (idx = 0) {return true; // returns false with break} alert ("name:" + item. name + ", value:" + item. value );});});

Ii. parse Json objects using jQuery:

JQuery provides another method "parseJSON", which requires a standard JSON string and returns the generated JavaScript Object. Let's look at the Syntax:

The Code is as follows:

Data = $. parseJSON (string );


Let's see how it is applied to actual development:

jQuery.ajax({ url: dataURL, success: function(results) { var parsedJson = jQuery.parseJSON(results); alert(parsedJson.name); } });

Supplement:

Example of jquery parsing json data:

Var data = "{root: [{name: '1', value: '0'}, {name: '000000', value: 'beijing'}, {name: '20140901', value: 'tianjin City '}, {name: '20160301', value: 'shanghai'}, {name: '20160301', value: 'chongqing '}, {name: '000000', value: 'weinan City '}, {name: '000000', value: 'yan'an City'}, {name: '000000', value: 'hanzhong City '}, {name: '000000', value: 'yulin City'}, {name: '000000', value: 'ankang City '}, {name: '200', value: 'shangluo City '}]} "; // if data is of the string type, convert the string type to the json data type var jsondatas = eval ("(" + data + ")"); $. each (jsondatas. root, function (I, n) {alert ("name" + n. name + "value" + n. value) ;}) // The following is an array string converted to a json string for parsing // json string var jsondata = "[{name: '1', value: '0'}, {name: '000000', value: 'xi'an '}, {name: '000000', value: 'tongchuan'}, {name: '000000 ', value: 'baoji City '}, {name: '000000', value: 'xianyang City'}, {name: '000000', value: 'weinan City '}, {name: '000000', value: 'yan'an '}, {name: '000000', value: 'hanzhong City'}, {name: '000000', value: 'yulin City '}, {name: '20160901', value: 'ankang City '}, {name: '20160901', value: 'shangluo City'}] "; var json = eval (jsondata ); $. each (json, function (I, n) {alert (json [I]. name); alert (json [I]. value); // according to the index value}); // json data characters do not need to be converted into var json = {"Products": [{"orderid": "11077 ", "customerid": "RATTC" },{ "orderid": "11078", "customerid": "RATT"}], "Img": [{"id ": "12345", "url": "image/1.jpg"}]}; $. each (json. products, function (I, n) {alert (n. orderid );})

Processing files (Handler. ashx)

If (context. Request. QueryString ["method"]! = Null) {string method = context. request. queryString ["method"]. toString (); if (method = "getlist") {string str = ConfigurationManager. connectionStrings ["ConnectionString"]. connectionString; SqlConnection conn = new SqlConnection (str); conn. open (); SqlCommand cmd = new SqlCommand (); cmd. connection = conn; cmd. commandText = "select ProID, ProName, url from Project where Adress = 'harbin '"; DataSet ds = new DataSet (); SqlDataAdapter da = new SqlDataAdapter (cmd); da. fill (ds); string sb = CreateJsonParameters (ds. tables [0]); context. response. clearContent (); context. response. write (sb. toString (); context. response. end ();}}}////// Construct a JSON string /////////
 Public string CreateJsonParameters (DataTable dt) {System. Text. StringBuilder sb = new System. Text. StringBuilder (); if (dt! = Null & dt. rows. count> 0) {sb. append ("["); for (int I = 0; I <dt. rows. count; I ++) {sb. append ("{"); for (int j = 0; j <dt. columns. count; j ++) {// if the value is not the last one, add commas to separate if (j <dt. columns. count-1) {sb. append ("/" "+ dt. columns [j]. columnName. toString () + "/": "+"/"" + dt. rows [I] [j]. toString () + "/", ");} // if the value is the last character, no comma (else if (j = dt) is added. columns. count-1) {sb. append ("/" "+ dt. columns [j]. columnName. toString () + "/": "+"/"" + dt. rows [I] [j]. toString () + "/" ") ;}// if it is the last value, no comma (if (I = dt) is added. rows. count-1) {sb. append ("}");} else {sb. append ("},") ;}} sb. append ("]"); return sb. toString () ;}else {return null ;}}

$. Ajax ({type: "POST", url: "Handler. ashx? Method = getlist ", async: false, // true indicates asynchronous false indicates synchronous contentType:" application/json ", dataType: 'json', success: function (result) {var temp = eval (result); // returns the array string for (var I = 0; I <temp. length; I ++) {o. innerHTML + = "Project name:" + result [I]. proName +"
Url: "+ result [I]. url +"
"; Datas + =" Project name: "+ result [I]. ProName +"
Url: "+ result [I]. url +"
";}Tiny. box. show (datas, 0, 0, 0, 1 );}});

I hope this article will help you with jQuery programming.

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.