python删除json中的所有特定键

2024-09-30 10:37:38 发布

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

使用python2.7,我想删除JSON中名为errCode和errMsg的所有键

我的JSON示例:

json_string = '''\
{
    "vacation": 
    [
        {
            "dates": [
                {
                    "duration": 360, 
                    "dateTo": "4.2.2014", 
                    "dateFrom": "2.1.2014"
                }
            ], 
            "worker": "8"
        }, 
        {
            "dates": [
                {
                    "duration": 420, 
                    "dateTo": "", 
                    "dateFrom": "29.01.2015",
                    "errCode": "1", 
                    "errMsg": "Missing dateTo"
                }
            ], 
            "worker": "2"
        }
    ], 
    "general": {
        "scriptComment": "", 
        "scriptTo": "", 
        "errCode": "2", 
        "errMsg": "Missing comment.", 
        "scriptFrom": "01.01.2014"
    }
}
'''

我不需要删除所有的错误代码


Tags: json示例stringgeneralworkerdatesdurationmissing
1条回答
网友
1楼 · 发布于 2024-09-30 10:37:38

将JSON解码为python字典,然后递归地删除键:

import json

def remove_error_info(d):
    if not isinstance(d, (dict, list)):
        return d
    if isinstance(d, list):
        return [remove_error_info(v) for v in d]
    return {k: remove_error_info(v) for k, v in d.items()
            if k not in {'errMsg', 'errCode'}}

data = json.loads(json_string)
data = remove_error_info(data)
json_string = json.dumps(data)

演示:

^{pr2}$

相关问题 更多 >

    热门问题