首页 > 解决方案 > 使用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"
        }
    ]

标签: pythonjsonfilterreplace

解决方案


你可以像这样寻找替换的钥匙

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)

推荐阅读