【问题标题】:Append data to json file if not in it already [duplicate]如果尚未将数据附加到 json 文件中[重复]
【发布时间】:2019-12-30 13:15:13
【问题描述】:

我有一个 .json 文件,我想将数据附加到该文件中。但前提是此字符串不在 .json 文件中。

JSON 文件:

[{"filename":"file1"}, {"filename":"file2"}, {"filename":"file3"}]

最终结果 JSON 文件:

[{"filename":"file1"}, {"filename":"file2"}, {"filename":"file3"}, {"filename":"file4"}]

我目前有这个:

with open('gdrivefiles.json', 'r') as f:
     filenameslist = json.load(f)    #Loads the .json file into a string (If I'm right)
for distro in filenameslist:
     filenames = distro["filename"]  #Gets a list of all the filenames

if name in filenames:
   print("yes")                      #If name is in the list of filenames print 'yes'
else:
   print("no")                       #If name is in the list of filenames print 'no'

(这段代码放在一个for循环中,所以它会为name的每个新值运行这段代码)

如果 json 文件中还没有 name ({"filename":"name"}),我该如何添加它?

【问题讨论】:

标签: python arrays json python-3.x visual-studio-code


【解决方案1】:

这段代码应该做你想做的:

import json

new_file = {"filename":"name"}

data = json.load(open("data.json"))
if not any([new_file['filename'] == x['filename'] for x in data]):
    data.append(new_file)

    json.dump(data, open("data.json","w"))

【讨论】:

  • 谢谢!这行得通!当它不在列表中时,我可以添加任何要执行的代码,对吗?如果我想在列表中执行代码 IS,我可以删除 not?
  • 是的,如果您只想在您的文件名已经在列表中的情况下运行代码,只需删除 not 运算符,并将您的代码放在 if 语句中。
【解决方案2】:

只需要在回写时创建数据结构:

import json

name = "file4"
with open('gdrivefiles.json', 'r') as f:
    filenameslist = json.load(f)

filenames = [distro["filename"] for distro in filenameslist]

if name in filenames:
    print("yes")                      #If name is in the list of filenames print 'yes'
else:
    print("no")                       #If name is in the list of filenames print 'no'
    filenames.append(name)

#  write filenames back to file as list of dicts!
with open('gdrivefiles.json', 'w') as f:
    f.write(json.dumps([{'filename': name} for name in filenames]))

【讨论】:

    【解决方案3】:
    import json
    
    new_object = {"filename":"file5"}
    
    with open('data.json') as json_file:
        data = json.load(json_file)
        if new_object not in data: 
          data.append(new_object)        
          json_file.close()
    
    with open('data.json', 'w') as outfile:
       json.dump(data, outfile)
       outfile.close()
    

    【讨论】:

      猜你喜欢
      • 2014-05-13
      • 2019-09-21
      • 2012-10-11
      • 2018-01-03
      • 1970-01-01
      • 2016-04-27
      • 2015-07-02
      • 1970-01-01
      相关资源
      最近更新 更多