Python如果json记录存在,请不要添加重复项

Python如果json记录存在,请不要添加重复项,python,json,Python,Json,所以基本上我只想检查json文件中是否已经存在json记录,如果存在,我不想添加它。有可能吗,伙计们?我就是搞不懂。我希望有人能帮助我。我会非常感激的 main.py with io.open('data.json', 'a', encoding='utf-8') as fp: for f in unique_following: data = {} data['insta'] = [] data['insta'].append({ 'id': f,

所以基本上我只想检查json文件中是否已经存在json记录,如果存在,我不想添加它。有可能吗,伙计们?我就是搞不懂。我希望有人能帮助我。我会非常感激的

main.py

with io.open('data.json', 'a', encoding='utf-8') as fp:
for f in unique_following:
    data = {}
    data['insta'] = []
    data['insta'].append({  
    'id': f,
    'dm': False
    })
    json.dump(data,fp,indent=1)

with open('data.json') as fp:
for f in unique_following:
    recipients=f
    print(text,recipients)
    time.sleep(5)
data.json

{
 "insta": [
  {
   "id": 6864438512,
   "dm": false
  }
 ]
}{
 "insta": [
  {
   "id": 7467167660,
   "dm": false
  }
 ]
}
{
 "insta": [
  {
   "id": 6864438512,
   "dm": false
  }
 ]
}
如果该记录写入data.json

{
 "insta": [
  {
   "id": 6864438512,
   "dm": false
  }
 ]
}{
 "insta": [
  {
   "id": 7467167660,
   "dm": false
  }
 ]
}
{
 "insta": [
  {
   "id": 6864438512,
   "dm": false
  }
 ]
}
我想要这个输出

{
 "insta": [
  {
   "id": 6864438512,
   "dm": false
  }
 ]
}{
 "insta": [
  {
   "id": 7467167660,
   "dm": false
  }
 ]
}

我将重新思考如何构造以及如何访问
data.json
。简单地将多个有效JSON字符串连接在一起不会产生一个更大的有效JSON字符串。事实上,结果根本无效

如果是我,我会使用某种数据库。否则,如果项目数量足够少,我会将所有数据放在一个列表中,然后用每个新项目更新列表。也许是这样:

with open('data.json') as fp:
    list_of_data = json.load(fp)

dirty = False
for f in unique_following:
    if not any(data['insta']['id'] == f for data in list_of_data):
        data['insta'] = [{'id': f, 'dm': False}]
        dirty = True
if dirty:
    with open('data.json', 'w') as fp:
        json.dump(fp, list_of_data, indent=1)
根据您的评论,您的新数据结构是一个带有一个键的
dict
insta
insta
的值是
dict
s的
列表

也许这项计划将有助于:

import json

# New data to add to the file
unique_following = ['7', '8', '9', '7']

# Read in existing file
with open('data.json') as fp:
    list_of_data = json.load(fp)

dirty = False
for f in unique_following:
    if not any(data['id'] == f for data in list_of_data['insta']):
        list_of_data['insta'].append({'id': f, 'dm': False})
        dirty = True
if dirty:
    # Write the file with new data
    with open('data.json', 'w') as fp:
        json.dump(list_of_data, fp, indent=1)

这些json有效吗?好吧,python可以处理它们,不,
data.json
不是json,python的
json
模块不会读取它。类似地,
我希望此输出
不是JSON,Python的
JSON
模块不会生成它。Python读取它:并将其写入数据。JSON:您肯定缺少逗号来分隔每个
insta
对象谢谢您的代码片段!最后,我创建了一个有效的json文件(我猜):但是当您的代码段读取它时,我得到了以下错误: