猿问

处理 Python 脚本中的索引位置以从 json 文件中删除 json 对象

我有一个文件(my_file.json),其内容如下;


[

            {

                "use":"abcd",

                "contact":"xyz",

                "name":"my_script.py",

                "time":"11:22:33"

             },

            {

                "use":"abcd"

                "contact":"xyz",

                "name":"some_other_script.py",

                "time":"11:22:33"

             },

            {

                "use":"apqwkndf",

                "contact":"xyz",

                "name":"my_script.py",

                "time":"11:22:33"

             },

            {

                "use":"kjdshfjkasd",

                "contact":"xyz",

                "name":"my_script.py",

                "time":"11:22:33"

             }

]

我使用以下 python 代码删除具有“name”的对象:“my_script.py”,


#!/bin/usr/python


impoty json


obj = json.load(open("my_file.json"))


index_list = []


for i in xrange(len(obj)):

     if obj[i]["name"] == ["my_script.py"]

      index_list.append(i)


for x in range(len(index_list)):

      obj.pop(index_list[x])


open("output_my_file.json","w".write(json.dumps(obj, indent=4, separators=(',',': ')))

但似乎我被卡住了,因为弹出索引后,实际 obj 中的索引位置发生了变化,这导致错误的索引删除或有时弹出索引超出范围。还有其他解决方案吗?


Smart猫小萌
浏览 165回答 5
5回答

呼啦一阵风

尝试以相反的顺序弹出:for x in reversed(range(len(index_list))):

PIPIONE

import jsonwith open('my_file.json') as f:    data = json.load(f)data = [item for item in data if item.get('name') != 'my_script.py']with open('output_my_file.json', 'w') as f:    json.dump(data, f, indent=4)

猛跑小猪

作为一般经验法则,您通常不想在迭代可迭代对象时对其进行更改。我建议你在第一个循环中保存你想要的元素:import jsonwith open('path/to/file', 'r') as f:    data = json.load(f)items_to_keep = []for item in data:    if item['name'] != 'my_script.py':        items_to_keep.append(item)with open('path/to/file', 'w') as f:    json.dump(items_to_keep, f, ...)过滤可以简化为一行(称为列表理解)import jsonwith open('path/to/file', 'r') as f:    data = json.load(f)items_to_keep = [item for item in data if item['name'] != 'my_script.py']with open('path/to/file', 'w') as f:    json.dump(items_to_keep, f, ...)

冉冉说

尝试:    import json    json_file = json.load(open("file.json"))    for json_dict in json_file:        json_dict.pop("name",None)    print(json.dumps(json_file, indent=4))你不需要最后一行“json.dumps”,我只是把它放在那里,这样打印时看起来更易读。

ABOUTYOU

这将创建一个新列表,并仅将那些没有的列表分配"name": "my_script.py"到新列表中。obj = [i for i in obj if i["name"] != "my_script.py"]
随时随地看视频慕课网APP

相关分类

Python
我要回答