英文:
Python change dinamically json key
问题
I have a specific JSON file that I read and change dynamically the value of key. I'm using this code to do this:
with open('payload/run_job.json', 'r+') as f:
data = json.load(f)
data['name'] = 'test'
result = json.dumps(data, sort_keys=True)
pprint(data)
and this is my JSON file
{
"name":"",
"template": {
"containers": [
{
"name_job": "",
"env": [
{
"name": "COUNTRY",
"value": ""
},
{
"name": "NAME",
"value": ""
},
{
"name": "ISTANCE_UUID",
"value": ""
}
]
}
]
}
}
Now I have to change also the value of name ISTANCE_UUID
into array object env. How can I do this?
英文:
I have a specific JSON file that I read and change dynamically the value of key. I'm using this code to do this:
with open('payload/run_job.json', 'r+') as f:
data = json.load(f)
data['name'] = 'test'
result = json.dumps(data, sort_keys=True)
pprint(data)
and this is my JSON file
{
"name":"",
"template": {
"containers": [
{
"name_job": "",
"env": [
{
"name": "COUNTRY",
"value": ""
},
{
"name": "NAME",
"value": ""
},
{
"name": "ISTANCE_UUID",
"value": ""
}
]
}
]
}
}
Now I have to change also the value of name ISTANCE_UUID
into array object env. How i can do this?
答案1
得分: 2
我认为您想要遍历容器,然后在每个容器内部遍历环境变量。当您找到所寻找的键的给定值时,可以更新该环境变量,然后跳出循环。
请注意,如果您控制数据格式,我建议将env
改为字典而不是键值对的列表。
data = {
"name": "",
"template": {
"containers": [
{
"name_job": "",
"env": [
{"name": "COUNTRY", "value": ""},
{"name": "NAME", "value": ""},
{"name": "ISTANCE_UUID", "value": ""}
]
}
]
}
}
for container in data["template"]["containers"]:
for env in container["env"]:
if env["name"] == "ISTANCE_UUID":
env["value"] = ["some", "list?"]
break
else: ## aka no_break
continue
break
import json
print(json.dumps(data, indent=4))
希望这有助于您的代码理解。
英文:
I think you want to iterate over containers and then over envs within each container. When you find the given value for the key you seek you can update that env then break out.
Note though, if you control the data format, I would look at altering it so that env
was a dictionary rather than a list of keys and values.
data = {
"name":"",
"template": {
"containers": [
{
"name_job": "",
"env": [
{"name": "COUNTRY", "value": ""},
{"name": "NAME", "value": ""},
{"name": "ISTANCE_UUID", "value": ""}
]
}
]
}
}
for container in data["template"]["containers"]:
for env in container["env"]:
if env["name"] == "ISTANCE_UUID":
env["value"] = ["some", "list?"]
break
else: ## aka no_break
continue
break
import json
print(json.dumps(data, indent=4))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论