这是一个json文件:
[
{
"userid": "7126521576",
"status": "UserStatus.OFFLINE",
"name": "Avril Pauling",
"bot": false,
"username": "None"
},
{
"userid": "7126521576",
"status": "UserStatus.OFFLINE",
"name": "Avril Pauling",
"bot": false,
"username": "None"
},
{
"userid": "6571627119",
"status": "UserStatus.OFFLINE",
"name": "Laverne Alferez",
"bot": false,
"username": "None"
},
{
"userid": "1995422560",
"status": "UserStatus.OFFLINE",
"name": "098767800",
"bot": false,
"username": "None"
}
]
删除重复的用户ID后的输出文件应该是:
[
{
"userid": "7126521576",
"status": "UserStatus.OFFLINE",
"name": "Avril Pauling",
"bot": false,
"username": "None"
},
{
"userid": "6571627119",
"status": "UserStatus.OFFLINE",
"name": "Laverne Alferez",
"bot": false,
"username": "None"
},
{
"userid": "1995422560",
"status": "UserStatus.OFFLINE",
"name": "098767800",
"bot": false,
"username": "None"
}
]
我尝试了以下代码,append()函数似乎无法正常工作;它只附加最后一项:
import json
with open('target_user.json', 'r', encoding='utf-8') as f:
jsons = json.load(f)
jsons2 = []
for item in jsons:
if item['userid'] not in json2:
jsons2.append(item)
with open('target_user2.json', 'w', encoding='utf-8') as nf:
json.dump(jsons2, nf, indent=4)
非常感谢快速帮助。
import json
with open('target_user.json', 'r', encoding='utf-8') as f:
jsons = json.load(f)
ids = set()
jsons2 = []
for item in jsons:
if item['userid'] not in ids:
ids.add(item['userid'])
jsons2.append(item)
with open('target_user2.json', 'w', encoding='utf-8') as nf:
json.dump(jsons2, nf, indent=4)