掌握JSON对象的结构、语法和实际应用
JSON对象是一个无序的键值对集合,使用大括号{}包裹。它是JSON中最常用的数据结构,用于表示复杂的数据实体。
{
"name": "张三",
"age": 30,
"isStudent": false
}
{
"firstName": "李四",
"lastName": "张"
}
{
"name": "王五",
"age": 25
}
{
"name": "赵六",
"age": 35,
"city": "上海"
}
{
"name": "钱七",
"age": 28
}
{
"string": "文本值",
"number": 42,
"boolean": true,
"nullValue": null,
"object": {
"nestedKey": "嵌套值"
},
"array": [1, 2, 3]
}
{
"firstName": "张",
"lastName": "三",
"age": 30
}
{
firstName: "张", // 键没有引号
'lastName': '三', // 使用单引号
"age": 30, // 末尾逗号
}
嵌套对象是指一个JSON对象中包含另一个JSON对象作为其属性的值。这种结构允许我们表示更复杂的数据关系。
{
"person": {
"name": "李四",
"age": 25
}
}
{
"user": {
"id": 12345,
"profile": {
"personal": {
"firstName": "王",
"lastName": "五"
},
"contact": {
"email": "wangwu@example.com",
"phone": "+8613812345678"
}
}
}
}
{
"company": "ABC科技有限公司",
"employees": [
{
"id": 101,
"name": "张三",
"department": "技术部"
},
{
"id": 102,
"name": "李四",
"department": "市场部"
}
],
"contact": {
"address": {
"street": "人民路123号",
"city": "北京",
"country": "中国"
},
"phone": "+861012345678"
}
}
{
"user": {
"id": 12345,
"name": "张三",
"age": 30,
"hobbies": ["阅读", "游泳", "编程"],
"address": {
"city": "北京",
"country": "中国"
}
}
}
// 假设jsonObj是解析后的JSON对象
const name = jsonObj.user.name;
const age = jsonObj.user.age;
const city = jsonObj.user.address.city;
// 适用于动态属性名或包含特殊字符的属性
const name = jsonObj.user["name"];
const hobby = jsonObj.user.hobbies[0];
const country = jsonObj.user.address["country"];
import json
# 假设json_string是JSON字符串
data = json.loads(json_string)
# 访问属性
name = data["user"]["name"]
age = data["user"]["age"]
city = data["user"]["address"]["city"]
hobby = data["user"]["hobbies"][0]
import org.json.JSONObject;
// 假设jsonString是JSON字符串
JSONObject jsonObj = new JSONObject(jsonString);
// 访问属性
String name = jsonObj.getJSONObject("user").getString("name");
int age = jsonObj.getJSONObject("user").getInt("age");
String city = jsonObj.getJSONObject("user").getJSONObject("address").getString("city");
{
"name": "张三",
"age": 30
}
// 点表示法
obj.newProperty = "新值";
// 括号表示法
obj["dynamicProperty"] = "动态值";
// 直接赋值
obj.existingProperty = "新值";
// 条件更新
if (obj.hasOwnProperty("property")) {
obj.property = "更新后的值";
}
// delete操作符
delete obj.propertyToDelete;
// 使用对象解构 (ES6)
const {propertyToDelete, ...newObj} = obj;
// 检查属性是否存在
if ("property" in obj) {
// 属性存在
}
// 检查属性是否存在且不为undefined
if (obj.hasOwnProperty("property")) {
// 对象拥有该属性
}
// for...in循环
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key + ": " + obj[key]);
}
}
// Object.keys() + forEach
Object.keys(obj).forEach(key => {
console.log(key + ": " + obj[key]);
});
// Object.entries() + forEach
Object.entries(obj).forEach(([key, value]) => {
console.log(key + ": " + value);
});
{
"user": {
"id": "u123456789",
"username": "johndoe",
"email": "john.doe@example.com",
"preferences": {
"theme": "dark",
"language": "zh-CN",
"notifications": {
"email": true,
"push": false,
"sms": true
}
},
"profile": {
"firstName": "John",
"lastName": "Doe",
"birthDate": "1990-05-15",
"avatar": "/images/avatars/u123456789.jpg"
}
}
}
{
"product": {
"id": "p987654321",
"name": "智能手机",
"brand": "TechBrand",
"price": {
"amount": 2999.99,
"currency": "CNY",
"discount": 0.1
},
"specifications": {
"display": "6.5英寸 OLED",
"processor": "八核 2.8GHz",
"memory": "8GB RAM + 128GB存储",
"camera": "48MP + 12MP + 5MP",
"battery": "4500mAh"
},
"inventory": {
"stock": 150,
"reserved": 25
},
"reviews": [
{
"user": "user123",
"rating": 5,
"comment": "非常好的手机!"
},
{
"user": "user456",
"rating": 4,
"comment": "性价比高,推荐购买"
}
]
}
}
{
"status": "success",
"code": 200,
"message": "数据获取成功",
"data": {
"page": 1,
"totalPages": 5,
"totalItems": 125,
"itemsPerPage": 25,
"items": [
{
"id": 1,
"title": "JSON教程",
"author": "张三",
"publishedDate": "2023-01-15",
"tags": ["JSON", "教程", "Web开发"]
},
{
"id": 2,
"title": "JavaScript高级编程",
"author": "李四",
"publishedDate": "2023-02-20",
"tags": ["JavaScript", "编程", "前端"]
}
]
},
"timestamp": "2023-10-05T14:30:00Z"
}
| 错误类型 | 错误示例 | 正确写法 | 说明 |
|---|---|---|---|
| 键未加引号 | {name: "张三"} | {"name": "张三"} | JSON键必须使用双引号 |
| 使用单引号 | {'name': '张三'} | {"name": "张三"} | JSON只支持双引号 |
| 末尾逗号 | {"name": "张三",} | {"name": "张三"} | 最后一个属性后不能有逗号 |
| 注释 | {/* 注释 */ "name": "张三"} | {"name": "张三"} | JSON不支持注释 |
| 未转义特殊字符 | {"path": "C:\Windows"} | {"path": "C:\\Windows"} | 反斜杠需要转义 |
| 未定义的值 | {"value": undefined} | {"value": null} | JSON没有undefined,使用null |