1

我有一个 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
        }
      }
      ]
}

使用 node js 完成此任务的任何直接方法?

4

1 回答 1

5

假设您真的是指 JavaScript 对象,请使用以下命令:

obj.elements[0].metadata.charge = 80;

如果您真的是指 JSON,那么先对其进行解析,然后再对其进行编码:

obj = JSON.parse( json );
obj.elements[0].metadata.charge = 80;
json = JSON.stringify( obj );
于 2013-07-31T12:40:44.340 回答