python - 如何在 python 3.x 中深度嵌套的 JSON 中分别更新/更改键和值(不是专用键值对)
问题描述
我有一个 JSON 文件,我需要在其中替换 UUID 并用另一个更新它。我无法替换深度嵌套的键和值。
下面是我需要在 python 中读取的 JSON 文件,替换键和值并更新文件。
JSON 文件 - myfile.json
{
"name": "Shipping box"
"company":"Detla shipping"
"description":"---"
"details" : {
"boxes":[
{
"box_name":"alpha",
"id":"a3954710-5075-4f52-8eb4-1137be51bf14"
},
{
"box_name":"beta",
"id":"31be3763-3d63-4e70-a9b6-d197b5cb6929"
}
]
}
"container": [
"a3954710-5075-4f52-8eb4-1137be51bf14":[],
"31be3763-3d63-4e70-a9b6-d197b5cb6929":[]
]
"data":[
{
"data_series":[],
"other":50
},
{
"data_series":[],
"other":40
},
{
"data_series":
{
"a3954710-5075-4f52-8eb4-1137be51bf14":
{
{
"dimentions":[2,10,12]
}
},
"31be3763-3d63-4e70-a9b6-d197b5cb6929":
{
{
"dimentions":[3,9,12]
}
}
},
"other":50
}
]
}
我想实现以下目标 -
"details" : { "boxes":[ { "box_name":"alpha" "id":"replace_uuid" }, } . . . "data":[ { "data_series": { "replace_uuid": { { "dimentions":[2,10,12] } } ]
在这种深度嵌套的字典中,我们如何用另一个字符串替换所有出现的键和值replace_uuid
呢?
我试过了 pop()
,dotty_dict
但我无法替换嵌套列表。
解决方案
我能够通过以下方式实现它 -
def uuid_change(): #generate a random uuid
new_uuid = uuid.uuid4()
return str(new_uuid)
dict = json.load(f)
for uid in dict[details][boxes]:
old_id = uid['id']
replace_id = uuid_change()
uid['id'] = replace_id
for i in range(n):
for uid1 in dict['container'][i].keys()
if uid1 == old_id:
dict['container'][i][replace_id]
= dict['container'][i].pop(uid1) #replace the key
for uid2 in dict['data'][2]['data_series'].keys()
if uid2 == old_id:
dict['data'][2]['data_series'][replace_id]
= dict['data'][2]['data_series'].pop(uid2) #replace the key
推荐阅读
- python - 如何使用 gspread python 将输出数据帧放置在 D2 而不是 A1 中的谷歌表格中
- vue.js - Vuetify如何覆盖分页组件的sass变量
- javascript - 如何传递文件的路径属性?反应
- xml - 在 xslt 样式表输出中保留实体而不使用字符映射
- python - 帕拉米科谈惠普供应
- python - 无法按照我的意愿调整列表
- r - 重新排列多个 GGPLOT2 图表和移动/调整比例时遇到问题
- python - Python子进程模块等待方法
- scala - 澄清为什么我不能通过它的子类型覆盖使用泛型类参数的方法
- sql-server - SSDT - 排除某些模式以及未命名的约束