JSON 对象数据类型是用大括号括起来的名称/值对的列表.
- JSON 对象非常类似于 javascript 对象.
- JSON 对象以键/值对形式编写.
- JSON 对象由大括号
{ }
括起来 . - 键必须是字符串,值必须是有效的 JSON 数据类型(字符串、数字、对象、数组、布尔值或 null).
- 键和值由冒号分隔.
- 每个键/值对都用逗号分隔.
JSON 对象示例是:
{
"name" : "Admin",
"age" : 36,
"rights" : [ "admin", "editor", "contributor" ]
}
1. 访问对象值
您可以通过两种方式访问对象值 :
1.1. 使用点 (.) 表示法
var author = {
"name" : "Admin",
"age" : 36,
"rights" : [ "admin", "editor", "contributor" ]
}
console.log( author.name );
//Output
Admin
1.2. 使用方括号 ([]) 表示法
var author = {
"name" : "Admin",
"age" : 36,
"rights" : [ "admin", "editor", "contributor" ]
}
console.log( author [ "name" ] );
console.log( author [ "age" ] );
//Output
Admin
36
2. 循环对象值
您可以使用 for 循环遍历对象值,就像循环遍历数组一样.
var author = {
"name" : "Admin",
"age" : 36,
"rights" : [ "admin", "editor", "contributor" ]
}
//Looping
for (x in author)
{
console.log(x + " - " + (author[x]));
}
//Output
name - Admin
age - 36
rights - admin,editor,contributor
3. 修改对象值
要修改对象值,请使用给定的两种方法之一:
3.1. 使用点 (.) 表示法
var author = {
"name" : "Admin",
"age" : 36,
"rights" : [ "admin", "editor", "contributor" ]
}
author.name = "Lokesh";
console.log( author.name );
//Output
Lokesh
3.2. 使用方括号 ([]) 表示法
var author = {
"name" : "Admin",
"age" : 36,
"rights" : [ "admin", "editor", "contributor" ]
}
author["name"] = "Lokesh";
author["age"] = 35;
console.log( author [ "name" ] );
console.log( author [ "age" ] );
//Output
Lokesh
35
4. 删除对象值
使用delete
关键字从 JSON 对象中删除属性:
delete author.name;