简体   繁体   English

如何删除 Python 中 JSON 文件中的特定值?

[英]How to remove a specific value in a JSON File in Python?

So I got a JSON File looking like所以我得到了一个 JSON 文件看起来像

{
    "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.我想要做的是使用 Python 的 JSON 模块或 Python 本身删除禁止的值 123。

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: del()pop()都基于元素的索引工作,您可以使用remove()方法删除元素,如下所示:

bannedjson["banned"].remove(123)

Note that remove() throws error if the element to be deleted does not exist in the list.请注意,如果要删除的元素在列表中不存在,则remove()将引发错误。 You can use the in clause to check before deleting:您可以使用in子句在删除之前进行检查:

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:此外, remove()仅删除第一次出现的元素,您可以使用列表推导删除所有元素:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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