更新json对象

时间:2018-02-07 21:08:20

标签: python arrays json

尝试更新json对象中的数组。这是我的json对象

   {
    "api.version": "v1",
    "source": {
        "thirdPartyRef": {
            "resources": [{
                "serviceType": "AwsElbBucket",
                "path": {
                    "pathExpression": "songs/*"
                },
                "authentication": {
                    "type": "S3BucketAuthentication"
                }
            }]
        }
    }
  }

读取json并更新awsId的代码。我的要求是在身份验证协议中添加aws信用。

程序成功运行后,它应该看起来像

       "authentication": {
          "type": "S3BucketAuthentication",
          "awsId": "AKIAXXXXX",
          "awsKey": "MYHSHSYjusXXX"
       }

这是我的代码片段args [5]是jsonfile

with open(args[5]) as json_data:
        source = json.loads(json_data.read())
#       source['source']['category']['awsID'] = "test"
source.update( {"awsId" : "AKIAXXXXX", "awsKey": "HHSJSHS"})
print source

输出:

{u'api.version': u'v1', 'awsKey': 'HHSJSHS', 'awsId': 'AKIAXXXXX', u'source': {u'thirdPartyRef': {u'resources': [{u'path': {u'pathExpression': u'songs/*'}, u'serviceType': u'AwsElbBucket', u'authentication': {u'type': u'S3BucketAuthentication'}}]}}}

我尝试source.update( "source":{"awsId" : "AKIAXXXXX", "awsKey": "HHSJSHS"}}),它会覆盖json的其余部分。

1 个答案:

答案 0 :(得分:4)

您想要更新的数据结构被深埋。您无法从最顶层访问它。

试试这个:

import json
with open('arg5.json') as json_data:
        source = json.loads(json_data.read())
print source
source["source"]["thirdPartyRef"]["resources"][0]["authentication"].update(
    {"awsId" : "AKIAXXXXX", "awsKey": "HHSJSHS"})