Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The js/jquery method of parsing the json and array formats is detailed


May 08, 2021 JSON


Table of contents


Before parsing, we have to figure out a few concepts: arrays, association arrays, and the differences and contact points between jason?

First, the concept of introduction

1, array

Grammar:
ECMAScript v3 specifies the syntax of array direct quantities, which JavaScript 1.2 and JScript 3.0 implement. Y ou can place a list of expressions separated by commas in square brackets, create and initialize an array. T he values of these expressions become array elements. For example:

var a = [1, true, 'abc'];

How to view the API.

ps: Must be separated by square brackets.


2, the associated array

(1) Grammar:

var myhash= {”key1″:”val1″, “key2″:”val2″ };//obj

(2)var

myhash= {key1:”val1″, key2:”val2″ };//obj-也可以

ps: It's almost the same as the jason format, but the jason format is more restrictive (the key pairs inside must use double quotes), but jason can only be used as a format standard and must be converted to an associated array object (obj) if you want to manipulate it.


2, simple operation
(1) Add key values to the Hash association array

// 添加一个新键 newkey ,键值为 newval
 myhash[”newkey”] = “newval”;

(2) Remove the key value of the hash association array

// 删除一个键 newkey ,同时,该键值对应的 newval 也就消失了
 delete myhash[”newkey”];

(3) Traversing the hash association array

// 遍历整个hash 数组 
 for (key in myhash) {
 val = myhash[key];
 }
(4)获得值
 方式1.myhash.key1
 方式2.myhash.key2

3、json
Format requirements:

"key1": "val1", "key2": "val2";

Second, several key points in the front background interaction

1. When the data sent by the server is not one json, but more than one, you should contact the array and the associated array to assemble the string
For example: var objs s. s. id: 1, name: 'n_1', s id: 2, name: 'n_2');

2. The data that the server gives to the client from start to finish is just a string, so in order for it to be able to do what is necessary in js, it can be converted to a js executable object by eval().
So the $.parseJSON() provided in jQuey is limited, and if this is the case mentioned in 1 above, it must be converted using eval() and then through $.each (objs, function (i, o) Take action

Third, the specific instance code

Page code:

The code is as follows:

<body>
 <input type="button" value="send ajax json" onclick="sendAjaxByjson();"/>
 <input type="button" value="send ajax array" onclick="sendAjaxByarray();"/>
</body>
 <script type="text/javascript">
  function sendAjaxByjson(){
   $.post("json",{},function(data){
    var obj=data;
    alert(typeof obj);//string
    //var a=eval(obj);不解,不注释则会报错..
    var strToobj=$.parseJSON(obj);
    alert(strToobj.name);
    alert(typeof strToobj)//obj
    var obja={'name':'techbirds','age':'23','sex':'male'};
    alert(typeof obja);//obj
    alert(obja['name']+":"+obja.age);
    delete obja['name'];
   });
  }
  function sendAjaxByarray(){
   $.post("array",{},function(data){
    var str=data;
    alert(typeof str);//string
    alert(typeof eval(str));//object
    var obja=[1,2,3,4,5];
    alert(typeof obja);//object

   });
  }
 </script>

Background code:

The code is as follows:

@Override
 protected void service(HttpServletRequest req, HttpServletResponse reps)
   throws ServletException, IOException {
  Map<String, Object> jsonMap=new HashMap<String, Object>();
  jsonMap.put("name", "techbirds");
  jsonMap.put("age", 23);
  jsonMap.put("sex", "male");
  reps.getWriter().print(JSONObject.fromObject(jsonMap).toString());
  reps.getWriter().flush();
  reps.getWriter().close();
 }

The code is as follows:

@Override
 protected void service(HttpServletRequest req, HttpServletResponse reps)
   throws ServletException, IOException {
  String array="[1,2,3,4,5,6]";
  reps.getWriter().print(array);
  reps.getWriter().flush();
  reps.getWriter().close();
 }

Jquery parses the json array string

A johnson string for an array of json objects:

var str=[{"Price":12,"Name":"aaa","Age",22},{"Price":24,"Name":"bbb","Age",33}];

In the fore desk, the parseJSON method of jquery is used for parsing, and the method of jquery's foreach is used for parsing, the code is as follows:

var jsonarray= $.parseJSON(str);
alert(jsonarray);
$.each(jsonarray, function (i, n)
{
    alert(n.Price);
}
For different versions of jquery, they also parse the string format of the json object array (I used two different versions of jquery, and I ran into this problem), and if the above code can't be parsed, wrap it up with the eval function, as follows:
var jsonarray= $.parseJSON(str);
$.each(eval("(" + jsonarray+ ")"), function (i, n) {
    alert(n.Price);
}
In the process of parsing the string of the jason object array, you can also use allert to eject the results of $.parseJSON (str) resolution, and if the object is displayed in the pop-up dialog box, the resolution is successful and can be passed through the object. The property name gets the value of the corresponding property, and if it does not pop up with object, wrap the object with eval() and get the value of the corresponding property.