Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove key/value pair in a json file in python

Tags:

python

json

{
    "duncan_long": {
        "id": "drekaner",
        "name": "Duncan Long",
        "favorite_color": "Blue"
    },
    "kelsea_head": {
        "id": "wagshark",
        "name": "Kelsea Head",
        "favorite_color": "Ping"
    },
    "phoenix_knox": {
        "id": "jikininer",
        "name": "Phoenix Knox",
        "favorite_color": "Green"
    },
    "adina_norton": {
        "id": "slimewagner",
        "name": "Adina Norton",
        "favorite_color": "Red"
    }
}

I am trying to Return a JSON list of all the users excluding the id of the user

like image 723
Tal Mosenzon Avatar asked Oct 27 '25 04:10

Tal Mosenzon


1 Answers

Assuming, the file in which you have your JSON is called file.json:

import json
with open('file.json') as f:
    d = json.load(f)
    for key, value in d.items():
        del value['id']
        d[key] = value

Alternative you can use the following:

import json
with open('file.json') as f:
    d = json.load(f)
    for key, value in d.items():
        value.pop('id', None) // this will not crash if the element has no key 'id'
like image 160
lmiguelvargasf Avatar answered Oct 30 '25 14:10

lmiguelvargasf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!