我有一个JSON如下:
{
"elements": [
{
"name": "F975CFAF-8FB4-2926-DD56-74CD230D15AF",
"uri": "vm/hpcloud/nova/large",
"parameters": {
"imageUri": "image/hpcloud/nova/ami-00001b03",
"securityGroups": [
"default"
]
},
"metadata": {
"name": "HPCloud Large VM with Ubuntu 10.04 With BitNami WebPack 1.2-0 Nova",
"description": "HPCloud Large VM with Ubuntu 10.04 With BitNami WebPack 1.2-0 Nova"
}
}
]
}
我需要按如下方式操作属性“元数据”(注意附加了新属性):
{
"elements": [
{
"name": "F975CFAF-8FB4-2926-DD56-74CD230D15AF",
"uri": "vm/hpcloud/nova/large",
"parameters": {
"imageUri": "image/hpcloud/nova/ami-00001b03",
"securityGroups": [
"default"
]
},
"metadata": {
"name": "HPCloud Large VM with Ubuntu 10.04 With BitNami WebPack 1.2-0 Nova",
"description": "HPCloud Large VM with Ubuntu 10.04 With BitNami WebPack 1.2-0 Nova",
"charge" : 80
}
}
]
}
使用节点js完成此任务的直接方法是什么?
答案 0 :(得分:5)
假设您真的是一个JavaScript对象,请使用:
obj.elements[0].metadata.charge = 80;
如果您真的是指JSON,那么请先解析它,然后再对其进行编码:
obj = JSON.parse( json );
obj.elements[0].metadata.charge = 80;
json = JSON.stringify( obj );