从Json文件中删除没有键的项~ Python

mrwjdhj3  于 2022-12-30  发布在  Python
关注(0)|答案(2)|浏览(132)

我有一个JSON文件,想删除某本书

[
  {
    "title": "How to love",
    "author": "vagabondage3",
    "isbn": 9832,
    "genre": "Comedy",
    "numofcopies": 2
  },
  {
    "title": "How to eat",
    "author": "belabor",
    "isbn": 2345,
    "genre": "Documentary",
    "numofcopies": 3
  },
  {
    "title": "hwo",
    "author": "TafaTIC",
    "isbn": 19,
    "genre": "Comedy",
    "numofcopies": 9
  }
]

要移除的部件

{
    "title": "hwo",
    "author": "TafaTIC",
    "isbn": 19,
    "genre": "Comedy",
    "numofcopies": 9
  }

json文件最后应该如下所示

[
  {
    "title": "How to love",
    "author": "vagabondage3",
    "isbn": 9832,
    "genre": "Comedy",
    "numofcopies": 2
  },
  {
    "title": "How to eat",
    "author": "belabor",
    "isbn": 2345,
    "genre": "Documentary",
    "numofcopies": 3
  }
]

老实说,我看到一个类似的例子,但我不能理解它,你能解释一下,请它是如何做的,谢谢提前〈3

gr8qqesn

gr8qqesn1#

最后,这取决于你如何识别你想要删除的文件。如果你想按索引删除,你可以试试这个:

json_data.pop(2)

或者你可以只使用一个条件进行迭代:

json_data = [item for item in json_data if item['title'] != 'hwo']
vcudknz3

vcudknz32#

您可以通过多种方式来实现:您可以使用del操作符按索引删除某本书:

del data_json[2]

或者,您可以使用pop()方法:

data_json.pop(2)

相关问题