alexchenco alexchenco - 1 month ago 6
JSON Question

How to append items to a file that contains a json array?

I'm trying to append

user_id
to
user_blacklist.json
:

def follow(self, user_id):
with open('user_blacklist.json', 'w') as fp:
json.dump(user_id, fp)


user_blacklist.json
looks like this:

{
"user_blacklist": [
"1691998847",
"1691998847",
"APPEND_NEW_ID_HERE"
]
}


But as you can see, I'm overwriting the whole file with
user_id
, instead of appending to the list. I'm sure it's easy, but I have zero experience with Python.

Answer

You have to read all json, add element and save all json.

with open('user_blacklist.json', 'r') as fp:
    data = json.load(fp)

data['user_blacklist'].append(user_id)

with open('user_blacklist.json', 'w') as fp:
    json.dump(data, fp)