如何在以下多维JSON数组中更新特定索引处的值?
我想更新放置在background-image
节点内的footer_logo
的值。
{
"Machine1": {
"sidebar_inner": {
"img": "img/pill.png",
"background-color": "#ffffff",
"side_logo": {
"background-image": "../footer_logo.png"
}
},
"lb_footer": {
"img": "img/bin.png",
"footer_logo": {
"background-image": "..img/footer_logo.png"
}
},
"machine_stand": {
"img": "img/machine_stand.png"
},
"side": {
"backgroundcolor": "#ccc"
}
}
}
答案 0 :(得分:3)
我添加了一个jsfiddle示例here。这很简单,请看下面的代码。
var myJson = {
"Machine1": {
"sidebar_inner": {
"img": "img/pill.png",
"background-color": "#ffffff",
"side_logo": {
"background-image": "../footer_logo.png"
}
},
"lb_footer": {
"img": "img/bin.png",
"footer_logo": {
"background-image": "..img/footer_logo.png"
}
},
"machine_stand": {
"img": "img/machine_stand.png"
},
"side": {
"backgroundcolor": "#ccc"
}
}
};
myJson.Machine1.lb_footer.footer_logo['background-image'] = 'New value.';
alert(myJson.Machine1.lb_footer.footer_logo['background-image']);
答案 1 :(得分:2)
要更新嵌套值,您可以将键(索引用于数组)链接在一起以查找适当的值。
这是代码,格式化以方便消费:
var obj = {"Machine1": {
"sidebar_inner": {
"img": "img/pill.png",
"background-color": "#ffffff",
"side_logo": {
"background-image": "../footer_logo.png"
}
},
"lb_footer": {
"img": "img/bin.png",
"footer_logo": {
"background-image": "..img/footer_logo.png"
}
},
"machine_stand": {
"img": "img/machine_stand.png"
},
"side": {
"backgroundcolor":"#ccc"
}
}}
更新“footer_logo”的背景图片:obj.Machine1.lb_footer,footer_logo.background-image = "something new";
更新“machine_stand”的img:
obj.machine_stand.img = "new/link.jpg";
// or use 'bracket notation', it's the same thing
obj['machine_stand']['img'] = "new/link.jpg"
答案 2 :(得分:1)
试试这个。工作jsfiddle
var json= '{"Machine1":{"sidebar_inner":{"img":"img\/pill.png","background-color":"#ffffff","side_logo":{"background-image":"..\/footer_logo.png"}},"lb_footer":{"img":"img\/bin.png","footer_logo":{"background-image":"..img\/footer_logo.png"}},"machine_stand":{"img":"img\/machine_stand.png"},"side":{"backgroundcolor":"#ccc"}}}';
var jsonObj = JSON.parse(json);
jsonObj.Machine1.lb_footer.footer_logo['background-image'] = 'abc';
答案 3 :(得分:0)
arr["Machine1"]["lb_footer"]["footer_logo"]["background-image"] = mynewvalue;