【问题标题】:use python replace json data key by keyword使用python用关键字替换json数据键
【发布时间】:2020-05-18 04:03:36
【问题描述】:

如何将旧的json从logic_1、logic_2全部keyname重命名为逻辑(去掉下划线和序列​​号)(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"
        }
    ]

【问题讨论】:

    标签: python json filter replace


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 非常感谢!!该代码帮助我使它工作!你真棒
    【解决方案2】:

    1.可以使用正则表达式匹配key 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
    

    【讨论】:

      猜你喜欢
      • 2017-09-19
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      • 2014-12-22
      • 2011-09-17
      • 1970-01-01
      • 2014-09-13
      • 2019-05-12
      相关资源
      最近更新 更多