Python 如何使用以下方法从json中删除项目?
我需要从json中删除数据,此时我正在使用以下代码:Python 如何使用以下方法从json中删除项目?,python,json,Python,Json,我需要从json中删除数据,此时我正在使用以下代码: import json with open('E:/file/timings.json', 'r+') as f: qe = json.load(f) for item in qe['times']: if item['Proc'] == 'APS': print(f'{item["Num"]}') del item json.dump(qe, f
import json
with open('E:/file/timings.json', 'r+') as f:
qe = json.load(f)
for item in qe['times']:
if item['Proc'] == 'APS':
print(f'{item["Num"]}')
del item
json.dump(qe, f, indent=4, sort_keys=False, ensure_ascii=False)
这不会从JSON中删除任何内容,下面是我的JSON文件的一个小示例
{
"times": [
{
"Num": "12345678901234567",
"Start_Time": "2016-12-14 15:54:35",
"Proc": "UPD",
},
{
"Num": "12345678901234567",
"Start_Time": "2016-12-08 15:34:05",
"Proc": "APS",
},
{
"Num": "12345678901234567",
"Start_Time": "2016-11-30 11:20:21",
"Proc": "Dev,
我希望它看起来像这样:
{
"times": [
{
"Num": "12345678901234567",
"Start_Time": "2016-12-14 15:54:35",
"Proc": "UPD",
},
{
"Num": "12345678901234567",
"Start_Time": "2016-11-30 11:20:21",
"Proc": "Dev,
正如您看到的,当进程被删除时,包含AP的部分是不好的做法,在迭代列表时删除元素 使用:
import json
with open('E:/file/timings.json', 'r') as f:
qe = json.load(f)
qe = [item for item in qe['times'] if item['Proc'] != 'APS'] #Delete Required element.
with open('E:/file/timings.json', 'w') as f:
json.dump(qe, f, indent=4, sort_keys=False, ensure_ascii=False)
del
在使用时,从会话中删除变量item
,但在数据结构中保留实际项不变。您需要明确地从数据结构中删除项所指向的内容。此外,您希望避免在迭代所述列表时从列表中删除项目。您应该重新创建整个列表:
qe['times'] = [item for item in qe['times'] if item['Proc'] != 'APS']
如果需要打印,可以使用以下方法:
def keep_item(thing):
if item['Proc'] == 'APS':
print thing['Num']
return False
else:
return True
qe['times'] = [item for item in qe['times'] if keep_item(item)]
可以使用以下方法从列表中删除元素:
for i,item in enumerate(qe['times']):
if item['Proc'] == 'APS':
qe['times'].pop(i)
然后写回JSON文件。您可以保存初始JSON,然后创建不包含“Proc”等于“APS”的项目的新JSON(此处为new\u JSON
),然后用该new\u JSON
覆盖JSON文件
import json
content = json.loads(open('timings.json', 'r').read())
new_json = {'times': []}
for item in content['times']:
if item['Proc'] != 'APS':
new_json['times'].append(item)
file = open('timings.json', 'w')
file.write(json.dumps(new_json, indent=4, sort_keys=False, ensure_ascii=False))
file.close()
您没有编写任何内容,请使用json转储的内容覆盖timings.json