Python如果json记录存在,不要添加dupli

2024-05-14 07:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

所以基本上我只想检查json记录是否已经存在于json文件中,如果存在,我不想添加它。有可能吗?我就是想不通。我希望有人能帮我。我真的很感激。你知道吗

主.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)

数据.json

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

如果记录写入数据.json

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

我想要这个输出

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

Tags: inidjsonfalsefordataaswith
1条回答
网友
1楼 · 发布于 2024-05-14 07:26:18

我会重新考虑如何构造和访问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)

根据您的注释,您的新数据结构是一个带有一个键的dictinstainsta的值是listdicts

也许这个计划会有帮助:

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)

相关问题 更多 >

    热门问题