处理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中的索引位置会发生变化,这会导致错误的索引删除,或者有时弹出索引超出范围。还有其他解决方案吗?

尝试按相反顺序弹出:

for x in reversed(range(len(index_list))):

这将创建一个新列表,并仅将没有"name": "my_script.py"的列表分配给新列表。

obj = [i for i in obj if i["name"] != "my_script.py"]
import json
with 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 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",我只是把它放在那里,这样打印出来时看起来更可读。

根据一般经验,在迭代时通常不希望更改可迭代项。我建议您在第一个循环中保存所需的元素:

import json
with 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 json
with 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, ...)

最新更新