var json = {
"workbookInformation": {
"version": "9.1",
"source-platform": "win"
},
"datasources1": {
...
},
"datasources2": {
...
}
}
我需要在workbookInformation
下添加新密钥对
var json={
"workbookInformation": {
"version": "9.1",
"source-platform": "win",
"new_key":"new_value"
},
"datasources1": {
...
},
"datasources2": {
...
}
}
json['new_key'] = 'new_value';
添加新密钥,但我想在“workbookInformation”
答案 0 :(得分:13)
有两种方法可以将新的键值对添加到JS中的Json对象
var jsObj = {
"workbookInformation": {
"version": "9.1",
"source-platform": "win"
},
"datasources1": {
},
"datasources2": {
}
}
1.使用点(。)
添加新属性jsObj.workbookInformation.NewPropertyName ="Value of New Property";
2.添加新属性,指定索引,如数组。
jsObj["workbookInformation"]["NewPropertyName"] ="Value of New Property";
最后
json = JSON.stringify(jsObj);
console.log(json)
答案 1 :(得分:2)
您的对象只是一个JavaScript对象,而不是JSON。您可以使用brackets notation
或点符号
json["workbookInformation"]["new_key"] = "new_value";
var json={
"workbookInformation": {
"version": "9.1",
"source-platform": "win"
}
}
json.workbookInformation.new_key = 'new_value';
console.log(json);

答案 2 :(得分:2)
如果要为json对象的每个键添加新的键和值,然后可以使用以下代码,则可以使用其他答案的代码 -
Object.keys(json).map(
function(object){
json[object]["newKey"]='newValue'
});
答案 3 :(得分:0)
这应该有效:
json.workbookInformation.new_key = 'new_value';
答案 4 :(得分:0)
json.workbookInformation.key = value;
答案 5 :(得分:0)
const Districts=[
{
"District": "Gorkha",
"Headquarters": "Gorkha",
"Area": "3,610",
"Population": "271,061"
},
{
"District": "Lamjung",
"Headquarters": "Besisahar",
"Area": "1,692",
"Population": "167,724"
}
]
Districts.map(i=>i.Country="Nepal")
console.log(Districts)
如果您具有JSON数组对象而不是简单的JSON。
const Districts= [
{
"District": "Gorkha",
"Headquarters": "Gorkha",
"Area": "3,610",
"Population": "271,061"
},
{
"District": "Lamjung",
"Headquarters": "Besisahar",
"Area": "1,692",
"Population": "167,724"
}
]
然后您可以映射它以添加新密钥。
Districts.map(i=>i.Country="Nepal");