删除json文件中的键抛出列表索引错误

时间:2019-04-30 19:20:32

标签: python json

我想从JSON文件中删除key:value并将其余的保存到单独的文件中。我要搜索的键是“操作”。 JSON内容为(input.json),如下所示:

{
    "name": "TEST_xxxxxx",
    "cmd.replication_definition":   {
        "tasks":    [{
                "task": {
                    "name": "TEST_xxxxxx"
                },
                "source":   {
                    "rep_source":   {
                        }
                },
                "targets":  [{
                        "rep_target":   {
                            "target_name":  "xxxxxx"
                        }
                    }],
                "manipulations":    [{
                        "name": "xxxxxx.xxxxxx_xxxxxx",
                        "table_manipulation":   {
                            "owner":    "xxxxxx",
                            "name": "xxxxxx_xxxxxx",
                            "source_table_settings":    {
                                "unload_segments":  {
                                    "ranges":   {
                                    },
                                    "entry_names":  {
                                    }
                                }
                            }
                        }
                    }, {
                        "name": "xxxxxx.xxxxxx_abcd",
                        "table_manipulation":   {
                            "owner":    "xxxxxx",
                            "name": "xxxxxx_OWNER",
                            "source_table_settings":    {
                                "unload_segments":  {
                                    "ranges":   {
                                    },
                                    "entry_names":  {
                                    }
                                }
                            }
                        }
                    }],
                "task_settings":    {
                    "source_settings":  {
                    },
                    "target_settings":  {
                    },
                    "sorter_settings":  {
                    },
                    "common_settings":  {
                        "change_table_settings":    {
                            },
                        "audit_table_settings": {
                            },
                        "apply_changes_enabled":    false,
                        "save_changes_enabled": true,
                        "dr_settings":  {
                        }
                    }
                },
                "configurations":   [{
                        "name": "xxxxxx.xxxxxx_xxxxxx"
                    }, {
                        "name": "xxxxxx.xxxxxx"
                    }]
            }],
        "databases":    [{
                "name": "xxxxxx",
                "description":  "Connection to Data Source",
                "role": "SOURCE"
            }]
    },
    "_version": {
        "version":  "1.1"
    }
}

我尝试了以下代码段:

import json

def remove_key(dat, keylist):
    print("\r\nEntering remove_key method...!!!\r\n")
    if len(keylist) > 1:
        print(data[keylist[0]])
        data[keylist[0]] = remove_key(data[keylist[0]], keylist[1:])
    else:
        del data[keylist[0]]

    print("Exiting remove_key method...!!!")
    return data

def main():
    print("Inside main method...!!!")
    your_file_to_read = 'input.json'
    your_file_to_write = 'output.json'
    your_key_to_delete = 'cmd.replication_definition:tasks:manipulations'
    with open(your_file_to_read, 'r') as read_file:
        raw_data = json.load(read_file)
    print("Now calling the remove_obfuscation method...!!!")
    result = remove_key(raw_data, your_key_to_delete.split(":"))
    print(result)
    #<place holder for write operation>
    print("Exiting main method...!!!")

if __name__ == "__main__": 
main()

函数运行后,我需要在output.json中输出如下:

{"name":"test",
 "cmd.replication_definition": {
 "tasks": {
        "task":"test",
        "source":"source",
        "targets":"target",
        "configurations":"config"
    },
"databases":"testdb"
},
 "versions":"1.0"
}

但是会引发以下错误:

Traceback (most recent call last):
  File "remove_obfs2.py", line 37, in <module>
    main()
  File "remove_obfs2.py", line 32, in main
    result = remove_key(raw_data, your_key_to_delete.split(":"))
  File "remove_obfs2.py", line 9, in remove_key
    data[keylist[0]] = remove_key(data[keylist[0]], keylist[1:])
  File "remove_obfs2.py", line 9, in remove_key
    data[keylist[0]] = remove_key(data[keylist[0]], keylist[1:])
  File "remove_obfs2.py", line 11, in remove_key
    del data[keylist[0]]
TypeError: list indices must be integers or slices, not str

1 个答案:

答案 0 :(得分:1)

您的函数无法处理特定级别的元素是列表而不是其他字典的情况。我想您想处理列表中的所有元素,因此需要添加一个循环。

def remove_key(data, [keylist][1]):
    print("\r\nEntering remove_key method...!!!\r\n")
    if len(keylist) > 1:
        print(data[keylist[0]])
        if type(data[keylist[0]]) is list:
            for el in data[keylist[0]]:
                remove_key(el, keylist[1:])
        else:
            data[keylist[0]] = remove_key(data[keylist[0]], keylist[1:])
    else:
        del data[keylist[0]]

    print("Exiting remove_key method...!!!")
    return data

DEMO