Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove value in JSON arrey

This is how I add values to the JSON file.

with open('data.json', 'r+') as f:
    json_datas = json.load(f)
    ids = json_datas["ids"]
    ids.append(user_id)
    json_new_datas = json.dumps({"ids": ids})
    f.seek(0)
    f.write(json_new_datas)

This is what the JSON file looks like:

{"ids": [447737210570276875, 528619819306713089, 447428922544488449, 780750434956607488]}

I’ve tried removing values like this but it doesn’t work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

with open('data.json', 'r+') as f:
    json_datas = json.load(f)
    ids = json_datas["ids"]
    ids.remove(user_id)
    json_new_datas = json.dumps(json_datas)
    f.seek(0)
    f.write(json_new_datas)

How do I remove the user_id?

>Solution :

It’s not working because you’re writing on top of existing content on your file, so if your array is like this:

{"ids": [447737210570276875, 528619819306713089, 447428922544488449, 780750434956607488]}

When you remove the last ID 780750434956607488, you’ll have an object like this:

{"ids": [447737210570276875, 528619819306713089, 447428922544488449]}

So when you try to write it on top of the existing file, the strings will overlap and you will have something like this:

{"ids": [447737210570276875, 528619819306713089, 447428922544488449]} 780750434956607488]}

Which breaks the file. One possible solution to your problem is to erase everything from the file first with the function f.truncate(0) and then write the new object :

with open('data.json', 'r+') as f:
    json_datas = json.load(f)
    ids = json_datas["ids"]
    ids.remove(user_id)
    f.seek(0)
    f.truncate(0)
    json_new_datas = json.dump({"ids": ids}, f)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading