I. BACKGROUND
JSON is a lightweight data interchange format that facilitates the interaction of Java services with JS, and this article describes the simple definition of JSON and how JS parses json.
Second, the content
1. JSON definition:
The simple JSON format is [{"Key1": "Value1"},{"Key2": "value2"}],
[] represents the array, {} is the data object in the array, Key1,key2 is a key in a JSON object, a key value in JSON is unique, value1,value2 is the value of the key key.
How to define:
1 directly spell the JSON string, example: String variable, content is [{"Attchname": "Annex 0", "Attchid": 0},{"Attchname": "Annex 1", "Attchid": 1},{"Attchname": "Annex 2", "Attchid": 2}].
2) Introduce Json-lib.jar open source jar package, define Jsonobject object, example:
Jsonarray Jsonarray = Newjsonarray ();
Jsonobject Attchjson = Newjsonobject ();
Attchjson.put ("Attchid", "0");
Attchjson.put ("Attchname", "annex 0");
Jsonarray.put (Attchjson);
Jsonarray is a JSON data, which is equivalent to using [] to define a JSON.
Complex JSON definition, the value of a key in JSON can also be a JSON array, for example, in JSON, where a task information is encapsulated, and several attachments are defined in this task as follows:
Jsonarray Taskjsonarray = Newjsonarray ();
Jsonobject taskjsonobj = Newjsonobject ();
Taskjsonobj.put ("TaskId");
Taskjsonobj.put ("TaskName", "MyTask");
Taskjsonobj.put ("Attchs", Jsonarray);
Taskjsonarray.put (Jsonobj);
Taskjsonarray for the last JSON content you want to get,
The form of a simple puzzle is as follows:
[{"Attchs": [{"Attchname": "Attachment 0", "Attchid": 0},{"Attchname": "Annex 1", "Attchid": 1},{"Attchname": "Annex 2", "Attchid": 2}], " TaskId ": M," TaskName ":" MyTask "}]
2. JS parsing json
The general parsing method for JSON:
var json = Eval_r (Jsonarray);
for (Var i=0;i<json.length;i++) {
alert ("Attchid: +json[i].attchid+", Attchname: "+json[i].attchname);
}
Parsing JSON using jquery:
$.getjson ("Jsontest", {shownumber: "3"},function (data) {$.each (data,function) {Idx,item (//alert
);
if (idx<0) {
returntrue;//with countinue, returns false with break
}
alert ("Attchid: +item.attchid+", TaskName: "+ item.attchname);
});
Third, summary
The JSON format is simple, easy to parse and generate, and is a lightweight data interchange format that is easy to use in web development.
The above is a small series for you to bring the JSON definition and jquery operation json method of all content, I hope to help you, a lot of support cloud Habitat Community ~