使用python将json数据键替换为关键字

2024-09-29 19:35:02 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将旧json从logic_1、logic_2所有键名重命名为logic(删除下划线和序列号)(ps:json文件中的数据通过循环get多数据)

[
    {
        "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"
        }
    ]

Tags: 文件数据jsongetnot重命名ps序列号
2条回答

您可以像这样寻找要更换的钥匙

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)

1.您可以使用正则表达式匹配密钥 2.然后在dict中添加一个新的键值。 3.然后删除旧的键值对

obj = re.compile('logic_\d*')
for dic in arr:
    match = obj.search(str(dic.keys())) # matching key
    if len(match.group) != 0:
       dic['logic'] = dic[match.group()] # adding a key value 
       del dic[match.group()] # deleting the old key value

相关问题 更多 >

    热门问题