S
S
septim5042020-12-16 23:36:51
Python
septim504, 2020-12-16 23:36:51

Python json how to delete an object?

i have json file

{
    "items": [
        {
        "date": "11.12.2020 22:35:37",
        "type": "buy",
        "game": "CS:GO",
        "balance": "10.9",
        "name": "Tec-9 | Re-Entry (Factory New)",
        "price": "0.77"
        },{
          
      "date": "16.12.2020 23:41:08",
      "type": "charging_fee",
      "game": "CS:GO",
      "balance": "0",
      "name": "Desert Eagle | Midnight Storm (Factory New)",
      "price": "0.36"
    },
    {
      "date": "16.12.2020 22:28:20",
      "type": "buy",
      "game": "CS:GO",
      "balance": "12.32",
      "name": "M4A1-S | Mecha Industries (Field-Tested)",
      "price": "5.43"
    }]
  
}
and a script that removes "type": "charging_fee"
with open('1.json') as json_data:
    data = json.load(json_data)
    
    
for sub_obj in data["data"]:
    if sub_obj["type"] == "charging_fee":
        sub_obj.pop("data")

with open('1.json', 'w') as outfile:  
    json.dump(data, outfile)
But it only removes the "type": "charging_fee" key and value, leaving the rest. And I need the object to be completely deleted, and in this case, json looked like this
{
    "items": [
        {
        "date": "11.12.2020 22:35:37",
        "type": "buy",
        "game": "CS:GO",
        "balance": "10.9",
        "name": "Tec-9 | Re-Entry (Factory New)",
        "price": "0.77"
        },
    {
      "date": "16.12.2020 22:28:20",
      "type": "buy",
      "game": "CS:GO",
      "balance": "12.32",
      "name": "M4A1-S | Mecha Industries (Field-Tested)",
      "price": "5.43"
    }]
  
}
. I would be grateful to anyone who can help, I myself am not a programmer, I tried to search on the Internet, I did not find

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Melnikov, 2020-12-17
@septim504

You can just make a new one without your

nd = [item for item in data['items'] if item["type"] != "charging_fee"]

If all your code is
import json

with open('1.json') as json_data:
    data = json.load(json_data)
    
nd = [item for item in data['items'] if item["type"] != "charging_fee"]

with open('1.json', 'w') as outfile:  
    json.dump(nd, outfile)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question