在JavaScript(JS)中,JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它基于JavaScript的一个子集。如果你想在已有的JSON对象中增加字段,可以直接通过点符号(.
)或者方括号([]
)来添加新的键值对。
以下是一些基本示例:
let jsonObj = {
"name": "John",
"age": 30
};
// 增加一个新的字段 "city"
jsonObj.city = "New York";
console.log(jsonObj);
// 输出: { name: 'John', age: 30, city: 'New York' }
let jsonObj = {
"name": "John",
"age": 30
};
// 增加一个新的字段 "city"
jsonObj["city"] = "New York";
console.log(jsonObj);
// 输出: { name: 'John', age: 30, city: 'New York' }
let jsonObj = {
"name": "John",
"age": 30
};
let newField = "country";
let newValue = "USA";
jsonObj[newField] = newValue;
console.log(jsonObj);
// 输出: { name: 'John', age: 30, country: 'USA' }
let jsonString = '{"name": "John", "age": 30}';
let jsonObj = JSON.parse(jsonString);
jsonObj.city = "New York";
let updatedJsonString = JSON.stringify(jsonObj);
console.log(updatedJsonString);
// 输出: {"name":"John","age":30,"city":"New York"}
...
)或者Object.assign()
方法来创建一个新的对象,该对象包含原始对象的所有字段以及新添加的字段。let jsonObj = {
"name": "John",
"age": 30
};
let updatedJsonObj = { ...jsonObj, city: "New York" };
console.log(updatedJsonObj);
// 输出: { name: 'John', age: 30, city: 'New York' }
优势:
应用场景:
领取专属 10元无门槛券
手把手带您无忧上云