What is JSON?
JSON: JAvaScript Object Notation (JavaScript object notation)
JSON is the syntax for storing and exchanging textual information. Similar to XML.
JSON is smaller, faster, and easier to parse than XML.
Example: This sites object is an array containing 3 site records (objects).
{"Sites": [{"Name": "Rookie Tutorial", "url": "Www.runoob.com"}, {"name": "Google", "url": "www.google.com"}, {"name": "Weibo", "url" : "Www.weibo.com"}]}
Two kinds of structure of JSON
JSON has two representations of structures, objects, and arrays.
1. The object structure begins with "{" Curly braces and ends with "}" curly braces. The middle section consists of 0 or more "key (key)" pairs consisting of "," separated by "/value", the keywords and values separated by ":", and the grammatical structure such as code.
{ key1:value1, key2:value2, ...}
Where the keyword is a string, and the value can be a string, a value, a true,false,null, an object, or an array
2. The array structure ends with "[" Start, "]". The middle consists of 0 or more lists of values separated by ",", grammatical structures such as code.
[ { key1:value1, key2:value2 }, { key3:value3, key4:value4 }]
JSON is a subset of JS, so it is easy to read and write JSON in JS. There are two ways to read and write JSON, respectively, using "." operator and the "[Key]" method.
We first define a JSON object with the following code:
var obj = { 1: "Value1", "2": "value2", count:3, person : [//array structure JSON object, can be nested using { id:1, Name: "Zhang San" }, { id:2, name: "John Doe" } ], object : {//Object structure JSON object id:1, msg: " Object in the object " } };
Use of JSON
1, reading data from JSON
function Readjson () { alert (obj.1);//Report syntax error, can use alert (obj["1"]), it is best not to do the keyword alert (obj.2) ; alert (obj.person[0].name); or alert (obj.person[0]["name"]) alert (obj.object.msg);//or alert (obj.object["MSG") }
2. Write data to JSON
For example, to add a piece of data to the JSON, the code is as follows:
function Add () { //Adds a record to the JSON object obj.sex= "male"//or obj["sex"]= "Male" }
JSON object after adding data
3. Modify the data in the JSON
We are now going to modify the value of count in JSON as follows:
function Update () { obj.count = 10;//or obj["Count"]=10 }
The modified JSON.
4. Delete data from JSON
We now implement the deletion of the count from JSON data, the code is as follows:
function Delete () { Delete obj.count; }
Post-Deletion JSON
You can see that count has been removed from the JSON object.
5, traversing the JSON object
You can use for...in ... Loop to iterate through the data in the JSON object, for example, we want to traverse the value of the output obj object, the code is as follows:
function traversal () { for (var. c in obj) { Console.log (c + ":", Obj[c]);} }
The program output results are:
Finish
A preliminary study of JSON