0

I have a .json file which I would like to append data to. But only if this string is not in the .json file already.

JSON File:

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

End result JSON File:

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

I currently have this:

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'

(This code is put in a for-loop, so it will run this code for every new value of name)

How would I add name ({"filename":"name"}) in the json file if it is not in it already?

WoJo
  • 500
  • 1
  • 3
  • 20
  • 3
    Does this answer your question? [How to append data to a json file?](https://stackoverflow.com/questions/12994442/how-to-append-data-to-a-json-file) – oo00oo00oo00 Dec 30 '19 at 13:17

3 Answers3

1

This code should do what you want:

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"))
Ed Ward
  • 2,333
  • 2
  • 10
  • 16
  • Thank you! This works! I can add any code to perform when it isn't already in the list right? And if I would want to perform code if it **IS** in the list I can just remove the `not`? – WoJo Dec 30 '19 at 13:28
  • Yeah, if you only want to run code if your filename is already in the list, just remove the `not` operator, and put your code inside the `if` statement. – Ed Ward Dec 30 '19 at 13:32
1

You just need to create the data structure when writing back:

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]))
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
0
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()
GihanDB
  • 591
  • 2
  • 6
  • 23