Python如果json记录存在不添加重复

时间:2018-04-12 18:32:22

标签: 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,
    '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
  }
 ]
}

因此,如果该记录写入data.json

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

我想要这个输出

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

1 个答案:

答案 0 :(得分:0)

我会重新考虑您的构建方式以及访问方式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,其中包含一个密钥:instainsta的值为list的{​​{1}}。

也许这个程序会有所帮助:

dict