Home >Web Front-end >JS Tutorial >Detailed explanation of how js/jquery parses json and array formats

Detailed explanation of how js/jquery parses json and array formats

高洛峰
高洛峰Original
2017-02-17 16:49:231137browse

Before parsing, we must clarify several concepts: What are the differences and contact points between arrays, associative arrays and json?

1. Concept introduction
1. Array

Syntax:
ECMAScript v3 specifies the syntax of array literals, and JavaScript 1.2 and JScript 3.0 implement it. You can create and initialize an array by placing a comma-separated list of expressions in square brackets. The values ​​of these expressions will become array elements. For example:

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

See the API for specific operations.

ps: Must be separated by square brackets.

2. Associative array

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

2.var
myhash= {key1:”val1″, key2:”val2″};//obj-can also

ps: almost the same as json format, but json format has more requirements Strict (the key-value pairs inside must use double quotes), but json can only be used as a format standard. If you want to operate on it, it must be converted into an associative array object (obj).

2. Simple operation
1. Add key value to Hash associative array

//Add a new key newkey, the key value is newval

myhash[”newkey ”] = “newval”;

2. Delete the existing key value of the Hash associative array

// Delete a key newkey, and at the same time, the newval corresponding to the key value will disappear
delete myhash[”newkey”];

3. Traverse the Hash associative array

// Traverse the entire hash array
for (key in myhash) {
val = myhash[ key];
}

4. Get the value

Method 1.myhash.key1
Method 2.myhash.key2

3.json
Format requirements:

{”key1″:”val1″, “key2″:”val2″};//Strictly follow this format, and the operation can be based on the operation of the associative array

2. Previous Several key points in background interaction
1. When the data sent by the server is not one json, but multiple jsons, the array and associative array should be connected to assemble the string
For example: var objs = [{ id : 1, name: 'n_1' }, { id: 2, name: 'n_2'}];

2. From beginning to end, the data provided by the server to the client is only a string, so in order to allow it to Perform necessary operations on it in js and convert it into a js executable object through eval().
Therefore, the $.parseJSON() provided in jQuey has limitations. If it is the situation mentioned in 1 above, you must use eval() for conversion, and then pass $.each(objs,function(i ,o){...}) to operate

3. Specific example code
Page code:

<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>


Backend code:

@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();
 }
 @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();
 }

More Please pay attention to the PHP Chinese website for related articles on how to parse json and array formats with multiple js/jquery!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn