简体   繁体   中英

How to remove a specific value in a JSON File in Python?

So I got a JSON File looking like

{
    "banned": [123, 456]
}

What I want to do is removing only the value 123 of banned if possible with Python's JSON Module or Python itself.

What I tried:

with open("banned.json", "w") as bannedload:
    bannedjson = json.load(bannedload)
    bannedjson["banned"].pop(123)
    # json.dump(bannedjson, bannedload) This Line was just for testing

Second try:

 with open("banned.json", "w") as bannedload:
    bannedjson = json.load(bannedload)
    del bannedjson["banned"][123]
    # json.dump(bannedjson, bannedload) This Line was just for testing

So does anybody know how to do this?

Both del() and pop() works based on index of the element, you can use remove() method to delete the element as:

bannedjson["banned"].remove(123)

Note that remove() throws error if the element to be deleted does not exist in the list. You can use the in clause to check before deleting:

elt = 123
if elt in bannedjson["banned"]: 
    bannedjson["banned"].remove(elt)

Further, remove() only removes the first occurrence of the element and you can use list comprehension to remove all elements as:

elt = 123
bannedjson["banned"] = [element for element in bannedjson["banned"] if elt != element]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM