JSON是一種基于文本的輕量級數據交換格式,因其簡單易讀、易于解析、可跨平臺、可嵌套使用而備受開發者喜愛,本文將會介紹JSON的增刪改查操作。
1. JSON增加
var data = { "name": "Tom", "age": 18, "sex": "male" }; // 往JSON對象里添加一個key-value data.city = "Beijing"; // 在一個數組里添加一個JSON對象 data.students.push({ name: "Lucy", age: 20, sex: "female" });
2.JSON 刪除
var data = { "name": "Tom", "age": 18, "sex": "male", "city": "Beijing", "students": [ { "name": "Lucy", age: 20, sex: "female" }, { "name": "Jack", age: 19, sex: "male" } ] }; // 刪除一個key-value delete data.city; // 刪除一個JSON對象 data.students.splice(0, 1);
3. JSON 修改
var data = { "name": "Tom", "age": 18, "sex": "male", "city": "Beijing", "students": [ { "name": "Lucy", age: 20, sex: "female" }, { "name": "Jack", age: 19, sex: "male" } ] }; // 修改一個key-value data.city = "Shanghai"; // 修改一個JSON對象 data.students[0].sex = "male";
4. JSON 查詢
var data = { "name": "Tom", "age": 18, "sex": "male", "city": "Beijing", "students": [ { "name": "Lucy", age: 20, sex: "female" }, { "name": "Jack", age: 19, sex: "male" } ] }; // 查詢一個key-value console.log(data.city); // 查詢一個JSON對象 console.log(data.students[0].age);
綜上所述,JSON的增刪改查操作非常簡單易用,為我們的開發工作提供了很大的便利。