我需要在使用以下代码时从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, 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,如您所见,当进程被移除时,包含APS的部分。
发布于 2019-02-27 10:21:35
您可以保存初始的json,然后创建不包含'Proc‘等于’new_json‘的项的新json,然后用该new_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()发布于 2019-02-27 10:17:38
在迭代列表时删除元素不是一个好做法。
使用:
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)发布于 2019-02-27 10:20:16
在使用del时,从会话中移除变量item,但在数据结构中保留实际项。您需要显式地从数据结构中移除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)]https://stackoverflow.com/questions/54902692
复制相似问题