gpt4 book ai didi

python - 替换 JSON 文件中 key 的值,可嵌套 n 层

转载 作者:太空狗 更新时间:2023-10-29 18:25:46 26 4
gpt4 key购买 nike

我有如下所示的 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)替换了“download_url”k:v。不幸的是,它仅替换了该 json 片段中的三个 download_urls 之一。我明白为什么,但在获得解决方案时遇到了一点困难,所以我在这里寻求帮助。

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

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

其中 download_url 是我分配给该变量的新值我需要做的是为任何名为 ["download_url"] 的 key 更新它,而不是我在我要去的层指定的那个。

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

我采用了之前在我的代码中获得的一些值,并构建了一个返回响应的 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"

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

最佳答案

使用递归

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/'}}}

关于python - 替换 JSON 文件中 key 的值,可嵌套 n 层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14882138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com