python - 使用python用关键字替换json数据键
问题描述
如何将旧的json从logic_1、logic_2所有keyname重命名为逻辑(删除下划线和序列号)(ps:json文件中的数据通过循环获取多数据)
[
{
"logic_1": "NOT",
"StudyDescription": "",
"SeriesDescription": "C\\+",
"ImageComments": ""
},
{
"logic_2": "NOT",
"StudyDescription": "\\-C",
"SeriesDescription": "\\-C",
"ImageComments": "\\-C"
}
]
至
[
{
"logic": "NOT",
"StudyDescription": "",
"SeriesDescription": "C\\+",
"ImageComments": ""
},
{
"logic": "NOT",
"StudyDescription": "\\-C",
"SeriesDescription": "\\-C",
"ImageComments": "\\-C"
}
]
解决方案
你可以像这样寻找替换的钥匙
import re
arr = [
{
"logic_1": "NOT",
"StudyDescription": "",
"SeriesDescription": "C\\+", "ImageComments": ""},
{
"logic_2": "NOT",
"StudyDescription": "\\-C",
"SeriesDescription": "\\-C",
"ImageComments": "\\-C",
},
]
for data in arr:
toswap = []
for key in data.keys():
match = re.search("_\d+$", key) # looking for _ followed by number
if match is not None:
new_key = key[0 : match.start()]
toswap.append((key, new_key,))
for key in toswap:
data[key[1]] = data[key[0]]
del data[key[0]]
print(arr)
推荐阅读
- google-cloud-platform - 错误:4 DEADLINE_EXCEEDED:Object.exports.createStatusError 已超过最后期限 - GCP
- kubernetes - 如何确保 GKE 中我的节点上只运行一个 pod?
- java - 为邻居过滤数组
- php - PHP Loop html组合具有相同值的表行
- python - 有没有一种简单的方法来扩展现有的激活函数?我的自定义 softmax 函数返回:一个操作对梯度有 `None`
- mysql - Laravel where 和 orWhere 函数
- ubuntu - 无法在 ubuntu 18.04 中安装 web3
- r - 如何使用udpipe获得动词的将来时
- javascript - OSM API 方式节点排序不正确
- pointers - 我如何找出有关无法运行的已编译 ELF 64 位 LSB 可执行文件(无效指针)的信息(它的作用和方式)?