Document directory
- Example
- Nested JSON object definition
What is JSON
JSON (JavaScript Object Notation) is a beautiful method for creating JavaScript objects.JSONIt is also a lightweight data exchange format. JSON is easy to read and write, and is also conducive to machine parsing and generation. JSON is a better way to exchange data in XML instead of AJAX.
The JSON definition method is similar to the direct definition method. The JSON definition method puts functions and attributes defined by the direct definition method in braces, and removes the object names of attributes and function signatures, change the equals sign to a colon, and change it to a comma after each line!
JSON format and syntax
var
jsonobject
=
{
//
Attribute syntax in the object (Attribute names and attribute values appear in pairs)
propertyname
:
value
,
//
Function syntax in the object (the function name and function content appear in pairs)
functionname
:
function
(
)
{
...;
}
};
- Jsonobject -- JSON Object Name
- Propertyname -- property name
- Functionname -- function name
- A pair of braces, including multiple "name/value" sets
- JSON is represented by a set of "name/value" pairs. It can also be understood as an Array)
- The attribute name or function name can be any string or even a null string (see the following example)
- Commas (,) are used to separate each pair of "name/value" pairs.
Example
var
site
=
{
URL
:
"
www.dreamdu.com
"
,
name
:
"
Mengzhidu
"
,
englishname
:
"
dreamdu
"
,
author
:
"
Cute monkey
"
,
summary
:
"
Free Webpage Design tutorial
"
,
pagescount
:
100
,
isOK
:
true
,
startdate
:
new
Date
(
2005
,
12
)
,
say
:
function
(
)
{
document
.
write
(
this
.
englishname
+
"
say : hello world!
"
)
}
,
age
:
function
(
)
{
document
.
write
(
this
.
name
+
"
Already
"
+
(
(
new
Date
(
)
.
getFullYear
(
)
)
-
this
.
startdate
.
getFullYear
(
)
)
+
"
Old!
"
)
}
};
The above is a typical JavaScript Object in JSON format. The object name is dreamdu, and each name and value use a colon:
Split, for example, the monkey value corresponding to the name author and the value corresponding to the name age 5.
Another example:
var
circle
=
{
x
:
6
,
y
:
8
,
r
:
5
}
;
The preceding definition defines an element with the x coordinate of 6, y coordinate of 8, and radius of 5.
Nested JSON object definition
var
sites
=
{
count
:
2
,
language
:
"
chinese
"
,
baidu
:
{
URL
:
"
www.baidu.com
"
,
name
:
"
Baidu
"
,
author
:
"
baidu
"
,
say
:
function
(
)
{
document
.
write
(
this
.
name
+
"
say hello
"
)
}
},
dreamdu
:
{
URL
:
"
www.dreamdu.com
"
,
name
:
"
Mengzhidu
"
,
author
:
"
monkey
"
,
say
:
function
(
)
{
document
.
write
(
this
.
name
+
"
say hello
"
)
}
}
};
The JSON representation of sites in the above example also contains two small JSON notation, so the JSON notation can be nested.