将JSON文件中的值替换为可以嵌套n级的键

时间:2013-02-14 19:03:37

标签: python json

我的JSON看起来像这样:

{
"ROLE_NAME": {
    "FOO": {
        "download_url": "http: //something.staging/12345/buzz.zip"
    },
    "BAR": {
        "download_url": "http: //something.staging/12345/fizz.zip"
    },
    "download_url": "http: //something.staging/12345/fizzbuzz.zip",
    "db_name": "somedb",
    "db_server": "dbserver.staging.dmz",
    "plugin": {
        "server_url": "http: //lab.staging.corp/server/"
    }
}
}

我写了一些python,用一个新值替换了“download_url”k:v(即new download_url)。不幸的是,它只替换了json片段中的三个download_urls中的一个。我理解为什么,但是在解决方案方面遇到了一些困难,所以我在这里寻求帮助。

整个json对象是“数据” 所以我做了这样的事情:

data["ROLE_NAME"]["download_url"] = download_url

其中download_url是我赋给该变量的新值 我需要做的是任何名为[“download_url”的键]然后更新它,而不是我在我要去的层指定的那个。

我的一些代码可以提供帮助:

我在前面的代码中获取了一些值并构建了一个返回响应的url。我从响应中提取一个值,用于构建download_url的值

buildinfo_url = "http://something.staging/guestAuth/app/rest/builds/?locator=buildType:%s,tags:%s,branch:branched:any" % (
    bt_number,
    list_json_load[role_name][0]['tag']
)

发送HTTP请求

client = httplib2.Http()
response, xml = client.request(buildinfo_url)

从响应xml中提取一些值并设置download_url变量

doc = ElementTree.fromstring(xml)
for id in doc.findall('build'):
    build_id = "%s" % (id.attrib['id'])
try:
    download_url = "http://something.staging/guestAuth/repository/download/%s/%s:id/%s" % (
        bt_number,
        build_id,
        build_artifact_zip
    )
    data[role_name]["download_url"] = download_url
except NameError:
    print "something"

我想我应该递归搜索和更新

1 个答案:

答案 0 :(得分:14)

使用递归

import json   
json_txt = """
{
"ROLE_NAME": {
    "FOO": {
        "download_url": "http: //something.staging/12345/buzz.zip"
    },
    "BAR": {
        "download_url": "http: //something.staging/12345/fizz.zip"
    },
    "download_url": "http: //something.staging/12345/fizzbuzz.zip",
    "db_name": "somedb",
    "db_server": "dbserver.staging.dmz",
    "plugin": {
        "server_url": "http: //lab.staging.corp/server/"
    }
}
}
"""
data = json.loads(json_txt)

def fixup(adict, k, v):
    for key in adict.keys():
        if key == k:
            adict[key] = v
        elif type(adict[key]) is dict:
            fixup(adict[key], k, v)

import pprint
pprint.pprint( data )

fixup(data, 'download_url', 'XXX')

pprint.pprint( data )

输出:

{u'ROLE_NAME': {u'BAR': {u'download_url': u'http: //something.staging/12345/fizz.zip'},
                u'FOO': {u'download_url': u'http: //something.staging/12345/buzz.zip'},
                u'db_name': u'somedb',
                u'db_server': u'dbserver.staging.dmz',
                u'download_url': u'http: //something.staging/12345/fizzbuzz.zip',
                u'plugin': {u'server_url': u'http: //lab.staging.corp/server/'}}}
{u'ROLE_NAME': {u'BAR': {u'download_url': 'XXX'},
                u'FOO': {u'download_url': 'XXX'},
                u'db_name': u'somedb',
                u'db_server': u'dbserver.staging.dmz',
                u'download_url': 'XXX',
                u'plugin': {u'server_url': u'http: //lab.staging.corp/server/'}}}