我想删除对象中的所有内容"name";在给定的json文件示例中,但保留对象,简而言之,我想清除对象。
{
"names": [
{
"player": "Player_Name",
"TB:": "12389",
"BW:": "596",
"SW:": "28",
"CQ:": "20"
}
]
}
我曾经尝试过这个代码:
with open('players.json', 'w') as w:
with open('players.json', 'r') as r:
for line in r:
element = json.loads(line.strip())
if 'names' in element:
del element['names']
w.write(json.dumps(element))
但它只是清除了整个json文件
抱歉我的英语不好
问题是打开同一个文件两次——同时进行读取和写入。此外,JSON不能逐行解析,只能作为一个整体进行解析。
import json
# 1. read
with open('players.json', 'r') as r:
data = json.load(r)
# 2. modify
# (you might want to check if data is a dict)
data['names'] = []
# 3. write
with open('players.json', 'w') as w:
data = json.dump(data, w)