SoFunction
Updated on 2025-03-09

Definition and value implementation code of JSON object in JS

(JavaScript Object Notation) A simple data format that is lighter than xml. JSON is a JavaScript native format, which means that processing JSON data in JavaScript does not require any special APIs or toolkits.

The rules of JSON are simple: an object is an unordered collection of "'name:value' pairs'. An object starts with "{" (open bracket) and ends with "}" (close bracket). Each "name" is followed by a ":" (colon); "'name/value' pair" is separated by "," (comma).

The rules are as follows:

1) Mapping is represented by a colon (":"). Name: Value
2) The data paralleled are separated by commas (","). Name 1: Value 1, Name 2: Value 2
3) The mapped collection (object) is represented by curly braces ("{}"). {name 1:value 1,name 2:value 2}
4) The set (array) of parallel data is represented by square brackets ("[]").
[
{name 1: value, name 2: value 2},
{Name 1: Value,Name 2: Value 2}
]
5) Types that element values ​​can have: string, number, object, array, true, false, null

Five ways to write:

1) Storing data in traditional ways and calling data

<script type="text/javascript">
//Define "class" under the traditional JS methodfunction Person(id,name,age){
 = id;
 = name;
 = age;
}
//Create "object" under the traditional JS methodvar p = new Person(20141028,"A small boat",22); 
//Calling attributes in the class to display the information of the Person();
();
();
</script>

2) The first style:

<script type="text/javascript">
var person = {
id:001,
name:"A small boat",
age:23
}
("serial number:"+);
("username:"+);
("age:"+);
</script>

3) The second style:

<script type="text/javascript">
var p = [
{id:001,name:"A small boat",age:22},
{id:002,name:"No regrets",age:23},
{id:003,name:"No regrets_a small boat",age:24}
]; 
 
for(var i = 0; i < ; i++){
("serial number:"+p[i].id);
("username:"+p[i].name);
("age:"+p[i].age);
 
}
</script>

4) The third style:

<script type="text/javascript">
var p = {
"province":[
{"city":"Fuzhou"},
{"city":"Xiamen"},
{"city":"Putian"}
]
};
("City:" + [0].city);
</script>

5) The fourth style:

<script type="text/javascript">
var p = {
"ids":[
{"id":001},
{"id":002},
{"id":003}
],
"names":[
{"name":"A small boat"},
{"name":"No regrets"},
{"name":"No regrets_a small boat"}
]
}; 
 
for(var i = 0; i < ; i++){
("name:"+[i].name); 
}
for(var i = 0; i < ; i++){
("id:"+[i].id);
}
 
</script>

6) The fifth style:

<script type="text/javascript">
var p = {
"province":["Fuzhou","Xiamen","Putian"]
};
("Number of cities:"+);
("Is:\n");
for(var i=0;i<;i++){
([i]);
}
</script>

I basically understand this article after reading this. You can write the code yourself and understand the mystery after running it.