JavaScript is a weakly typed language, and the system iterates through the JSON data to sort by its own data type, as follows:
| The code is as follows |
Copy Code |
| <script Src= "Jquery.js" ></script> <script> var json1 = { "2": {"name": "1th"}, "1": {"name": "2nd"}, "3": {"name": "3rd"} } var json2 = { "2_str": {"name": "1th www.111cn.net"}, "1_str": {"name": "2nd"}, "3_str": {"name": "3rd"} } $.each (Json1, function (i,item) { alert (i+ ":" +item.name); }); $.each (json2, function (i,item) { alert (i+ ":" + Item.name); }); </script> |
How to sort JSON data by a specified sort:
| The code is as follows |
Copy Code |
| <script src= "Jquery.js" ></script> <script type= "Text/javascript" > var json = {"Languages": [ {"id": "1", "name": "PHP", "Sort": "1"}, {"id": "2", "Name": "Jacscript", "Sort": "3"}, {"id": "3", "Name": "PYTHON", "Sort": "4"}, {"id": "4", "Name": "NODE." JS ", sort": "2"} ]};
Sort before www.111cn.net $.each (json.languages, function (i) { Alert (json.languages[i].id+ "" +json.languages[i].name+ "Sort:" +json.languages[i].sort); });
To sort json["Languages"].sort (function (a,b) { return a["Sort"] > b["Sort"]? 1: (a["sort"] = = b["Sort"]? 0:-1); });
After sorting $.each (json.languages, function (i) { Alert (json.languages[i].id+ "" +json.languages[i].name+ "Sort:" +json.languages[i].sort); }); </script> |
The
primarily uses the sort method of JavaScript to sort the data in the specified way.