JSON (JavaScript Object Notation) is a simple data format that is lighter than XML. JSON is a native JavaScript format, which means that working with 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 "{" (opening parenthesis) and "}" (the closing parenthesis) ends. Each "name" is followed by a ":" (colon); "' Name/value ' pair ' is separated by", "(comma).
Here are some examples of JSON for some simple introduction:
One, you can convert a string that conforms to a certain format into a JSON object by using the Eval function in JavaScript
<script language= "JavaScript" >
function showjsonstring ()
{
Response = (
"[{name: ' Joe ', Age: ' ' ', ' Gender: ' m '},{name: ' Chandler ', Age: ' + ', Gender: ' M '},{name: ' Rose ', Age: ' + ', Gender: ' m '}] "//String form
);
var response1 = "({name: ' Vicson ', Age: ' + ', Gender: ' M '})"; String form, where the parentheses cannot be small
JSON = eval (response);
Json1 = eval (response1);
Alert (Json[0].name + "," + Json[1].age + "," + Json[2].gender);
alert (json1.name);
}
Showjsonstring ();
</script>
Second, directly define the JSON object
<script language= "JavaScript" >
function Showjsonobject ()
{
var user =
{
Username: "Andy",
"Age": 20,
"Info": {"tel": "25003614", "cellphone": "882"},
"Address":
[
{City: "Shenzhen", "Postcode": "0755"},
{"City": "Guangzhou", "Postcode": "020"}
]//address is an array
}//Object form
alert (user.username);
alert (user.age);
alert (User.info.cellphone);
alert (user.address[0].city);
alert (User.address[0].postcode);
}
Showjsonobject ();
</script>
Iii. assigning values to the properties of a JSON object
<script language= "JavaScript" >
function Setjsonobject ()
{
var user=
{
"username": "Andy"
}
User.username = "Tom";
alert (user.username);
}
Setjsonobject ();
</script>
To convert a string into a JSON object through the Parsejson method in Json.js,
Json.js package can be downloaded in http://www.json.org/json-zh.html
<script language= "javascript" src= "Json.js" ></script>
<script language= "JavaScript" >
function Parsejsoneval ()
{
var str = ' {' name ': ' Violet ', ' occupation ': ' character '} ';
var obj = Str.parsejson ();
Alert (obj.tojsonstring ());
alert (obj.name);
}
Parsejsoneval ();
</script>
JS encapsulated JSON data