How to operate JSON on the JQuery front-end

Reprinted from: Weidian Reading   https://www.weidianyuedu.com

1. About the data format of Json

From a structural point of view, all data can ultimately be divided into three types:

the first type is scalar (scalar), which is a separate string (string ) or number (numbers), such as The word "Beijing" alone.

The second type is sequence , that is, several related data are arranged together in a certain order, also called array or List, such as "Beijing, Tokyo".

The third type is mapping, which is a name/value pair (Name/value), that is, the data has a name and a corresponding value, which is also called hash or

dictionary . (Dictionary), such as "Capital: Beijing".

JSON (JavaScript Object Notation) is a lightweight data exchange format. Its rules are very simple and interesting:

1) Parallel data are separated by commas (",").

2) Mapping is represented by colon (":"). 3) Collections ( arrays

) of parallel data are represented by square brackets ("[]"). 4) The mapped collection (object) is represented by curly brackets ("{}"). According to this rule, the following understanding can be made: 1. Arrays are created with "[]", objects are created with "{}", and Json is basically an array or object created with [] or {}, otherwise it is an ordinary string. is meaningless; 2. Whether it is an array or an object, the elements between them are separated by ","; 3. Inside the object, the name and value (of the attribute) are separated by ":", and must be separated by ":" ” separated, attribute names or values ​​cannot exist alone; 4. Objects and arrays can be nested in each other, that is, an element in an array can be an object or an array, and similarly the value of an attribute in an object can be an The object can also be an array. One of the most common uses of JSON is to read JSON data from a web server (as a file or as an HttpRequest), convert the JSON data into a JavaScript object, and then use the data in the web page. Or conversely, convert the parameter into a JSON object, then deserialize it into an object in the background, and then obtain the value of the parameter. This can solve the shortcoming of the callback method that can only pass one parameter. Use the JSON object as the parameter of the Callback. 2. Json data form Example 1. var china= {beijing:{name:"Beijing",area:"16000",haidian:{name:"Haidian District"}}, shanghai:{name:"Shanghai",area:"10000",minhang :{name:"Minhang District"}}}; alert(china.beijing.haidian.name); alert(china.shanghai.minhang.name); "Haidian District" and "Minhang District" pop up respectively. 2. var ourcountry=[["Beijing City"],["Shanghai City"],["Hefei City","Wuhu City","Bengbu City"]]; alert(ourcountry[2][1]); pop-up "Wuhu". 3. var zhongguo = {provinces: [{name: "Beijing", cities: [{name:"Beijing City", quxian: ["Haidian District", "Chaoyang District", "Dongcheng District", "Xicheng District"] } ] }, {name: "Anhui Province", cities:[{ name: "Wuhu City", quxian: ["Fanchang County", "Wuhu County", "Nanling County", "Sanshan District"] }, { name :"Hefei City", quxian: ["Feixi County","Shushan District","Luyang District"] }]}, "Hubei Province" ] }; var str ="China: {\n"; for (var i = 0;i < zhongguo.provinces.length; i++) { if (zhongguo.provinces.cities !=null) { str += zhongguo.provinces.name+"{"; for (var j = 0; j < zhongguo. provinces.cities.length; j++) { if (zhongguo.provinces.cities[j] !=null) { str +=zhongguo.provinces.cities[j].name +"{"; for (var k = 0; k <zhongguo.provinces.cities[j].quxian.length; k++) { str +=zhongguo.provinces.cities[j].quxian[k]; if (k != zhongguo.provinces.cities[j].quxian. length - 1) { str +=",





















































































































}

}

3. Convert the string returned by the server into a Jsond object in the foreground. The

client can easily submit data to the server through the address bar or post. However, after the server processes the data, it will return the calculated result information to the client. There is a certain degree of difficulty in terminal operation, especially when the amount of data is large. At this time, the format of the data becomes the key. Data can be easily assembled according to a certain format, and then analyzed easily. Using Json is a good strategy. On the server side, a string is assembled in Json format and responded to the client. How does the client perform parsing? There are generally two strategies (the names of the two strategies are the names given by yourself, which may not be very reasonable, but the idea should be no problem):

1. Directly parse

var json = eval("(" + result + ")") ;

Through the above expression, the Json format string that the server responds to the client is parsed into a Json (formatted) object named "json", through "json." or "json[]" Data can be accessed in this way.

2. Indirectly parse

var json = "r=" + result;

eval(json);

Of course, the above line of code can be merged into: eval("r=" + result);

Through the above calculation, the server-side response can also be sent to the client The Json format string on the end is parsed into a Json (formatted) object, but the object name is "r", and data can be accessed through "r." or "r[]".

Summary: Json is a simple data exchange format. It can almost replace xml to flexibly exchange data between servers.

4. Directly request JSON data files.

Many interfaces directly provide a URL request link. JSON data or XML data can be returned according to the parameter format of the URL. At this time, you can directly initiate a URL request in Jquery to directly obtain the JSON data

$.getJSON( "/baiying/data.html",function(data) { tr2detail_data = data.train_info; tr2list_data = data.station_list; RenderObj.ControlList["checiInforender"].Refresh(); RenderObj.ControlList["checiDetailrender"].Refresh( ); }) $.getJSON("test.json",function(data){ for (var i = 0; i <data.rows.length; i++) { $("#test").append("<p >"+ data.rows[i].realName + "</p>"); } }); 5. Arrays and objects in JavaScript In JavaScript, the data format usually created with [] is called an array, with { }The things you create are called objects. There is an array a=[1,2,3,4] and an object a={0:1,1:2,2:3,3:4}, run alert(a[1]), two kinds The results are the same! That is to say, data collections can be represented by arrays or objects, so which one should be used? In fact, arrays represent collections of ordered data, while objects represent collections of unordered data. If the order of the data is important, use an array, otherwise use an object. 6. JSON.parse(str) and JSON.stringify(a): 1.parse is used to parse a json object from a string. For example, varstr="{"name":"cpf","age":"23"}" is obtained through JSON.parse(str): Object: age:"23" name:"cpf" _proto_:Object ps:single quote Written outside {}, each attribute must be double quoted, otherwise an exception will be thrown. 2. stringify is used to parse a string from an object, for example, var a={a:1,b:2} via JSON.stringify( a) Get: "{"a":1,"b":





















































































































var obj = JSON.parse(str); // --> parse error

name is not enclosed in quotes. When using JSON.parse, an exception will be thrown in all browsers and the parsing will fail. The first two methods are fine.

4. Convert JSON into a string.

It is generally used when debugging alerts. It is used to view JSON object details

JSON.stringify(res)

Guess you like

Origin blog.csdn.net/xinyuerr/article/details/133764058