使用python从json文件中删除数组元素

mf98qq94  于 2023-02-26  发布在  Python
关注(0)|答案(2)|浏览(323)

我想从下面的JSON文件中删除整个元素数组。我是一个很新的JSON。请帮助。

    • 输入**:

ABCD12:

{

   "code": "ab11",

   "Number": 123456,

   "Name": "aaaaaa",

   "Element": [

             {
                          "abc": "123", 
                          "Center": "123",
                          "Description": "your description here", 
              },
              {
                          "Cdf": "456", 
                          "Color": "blue",
                          "Shape": "round", 
              }

],
  "Animal": "tiger",

  "Bird": "eagle",

  "Flower": "rose"
  }

CDEF34:

{

   "code": "cd12",

   "Number": 7891011,

   "Name": "bbbbb",

   "Element": [

             {
                          "abc": "345", 
                          "Center": "456ab",
                          "Description": "your description", 
              },
              {
                          "Cdf": "567", 
                          "Color": "grey",
                          "Shape": "circle", 
              }

],
  "Animal": "dog",

  "Bird": "crow",

  "Flower": "sunflower"
  }
    • 输出**:

ABCD12:

{

   "code": "ab11",

   "Number": 123456,

   "Name": "aaaaaa",

  "Animal": "tiger",

  "Bird": "eagle",

  "Flower": "rose"

  }

CDEF34:

{

   "code": "cd12",

   "Number": 7891011,

   "Name": "bbbbb",

  "Animal": "dog",

  "Bird": "crow",

  "Flower": "sunflower"

  }

我尝试将json保存在一个名为file.json的文件中,并在python中执行以下代码

import json

with open("file.json") as f:

       data= json.load(f)

f.pop(data["wbsElement"]) 

with open("file.json", "w") as f: 

       json.dump(data, f)

但没有帮助。

c6ubokkw

c6ubokkw1#

您执行了:

data = json.load(f)

f.pop(data["wbsElement"])

你想要的是沿着于

del data["wbsElement"]

data.pop("wbsElement")

https://docs.python.org/3/library/stdtypes.html#dict.pop

2wnc66cl

2wnc66cl2#

因为"Element"是一个嵌套的值而不是键,所以一种方法是循环遍历这些值。

import json

with open("file.json") as f:
    data= json.load(f)

for obj in data.values():
    del obj['Element']
    # or
    # obj.pop("Element")

with open("file.json", "w") as f: 
    json.dump(data, f)

相关问题