Home > Software design >  Remove value in JSON arrey
Remove value in JSON arrey

Time:02-17

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:

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?

CodePudding user response:

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)

CodePudding user response:

What you have is a pairing "json_datas" with key-value pair: id:[list] the key "ids" is paired with a list. try changing ids.remove(value) to ids.remove(index).

Besides .remove(), there's also del list[index] and splice for similar effect. Beware, when you del, your list size gets (-1) smaller so your next del index should be adjusted

  • Related