1. Background
json is a lightweight data exchange format, which is very conducive to the interaction between Java services and js. This article will introduce the simple definition of json and how to parse json by js.
II. Content
1. json definition:
The simple json format is [{"key1":"value1"},{"key2":"value2"}],
[] represents the array, {} represents the data object in the array, key1 and key2 are the key in a json object, and the key value in a json is unique, value1 and value2 are the values corresponding to the key key.
Definition method:
1) Directly spell the json string, example: String variable, the content is [{"attchName":"attachment 0","attchId":0},{"attchName":"attachment 1","attchId":1},{"attchName":"attachment 2","attchId":2}].
2) Introduce open source jar package and define JSONObject objects, example:
JSONArray jsonArray = newJSONArray(); JSONObject attchJson = newJSONObject(); ("attchId","0"); ("attchName", "Attachment 0"); (attchJson);
jsonArray is a json data, which is equivalent to defining a json with [].
Complex json definition, the value corresponding to the key in json can also be a json array. For example, json encapsulates a task information. There are several attachment definition methods in this task as follows:
JSONArray taskJsonArray = newJSONArray(); JSONObject taskJsonObj = newJSONObject(); ("taskId",100); ("taskName", "myTask"); ("attchs",jsonArray); (jsonObj);
taskJsonArray is the json content you want to get in the end,
The form after a simple string is as follows:
[{"attchs":[{"attchName":"attachment0","attchId":0},{"attchName":"attachment1","attchId":1},{"attchName":"attachment2","attchId":2}],"taskId":100,"taskName":"myTask"}]
2. JS parsing json
General parsing method of json:
var json = eval_r(jsonArray ); for(var i=0;i<;i++){ alert("attchId:"+json[i].attchId+",attchName:"+json[i].attchName); }
Use jquery to parse json:
$.getJSON("jsonTest",{showNumber:"3"},function(data){ $.each(data,function(idx,item){ //alert(idx); if(idx<0){ returntrue;//Same country, return false and break } alert("attchId:"++",taskName:"+); }); });
3. Summary
The json format is simple, easy to parse and generate, and is a lightweight data exchange format that is easy to use in web development.
The above is the full content of the json definition and jquery operation method brought to you by the editor. I hope it will be helpful to everyone and support me more~