skip to Main Content

I want to remove whole Element array from this below json file. I am quite new in json. Please help.

Input:

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"
  }

Output:

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"

  }

I tried to keep the json in a file called file.json and executed below code in 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)

But no help.

2

Answers


  1. You executed:

    data = json.load(f)
    
    f.pop(data["wbsElement"])
    

    What you wanted was something along the lines of

    del data["wbsElement"]
    

    or

    data.pop("wbsElement")
    

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

    Login or Signup to reply.
  2. Because "Element" is a nested value and not a key, one approach is to loop through the values. Your code should look like:

    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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search