Python - remove item from Dict/List

18,256

Solution 1

Load it with json, then remove the key if it's empty:

import json
item =json.loads(src)
if 'product_language' in item and not item['product_language']:
    item.pop('product_language')

in Python, empty strings are equal to False.

Solution 2

use json module to load the json.

import json

with open('demo.txt','r+') as f:
    dic=json.load(f)

    try:
        if dic['metadata']["product_language"]:
            del dic['metadata']["product_language"]
    except KeyError:
        print "Key doesn't exist"
    print dic

Note that, here dic is a dictionary, you can be sure about it by printing type(dic). So, you can can perform any dictionary operation on it, for example, I deleted a key of dic. To iterate through the dic, do:

for key,value in dic.iteritems():
    #do_something
Share:
18,256
user3092876
Author by

user3092876

Updated on June 19, 2022

Comments

  • user3092876
    user3092876 almost 2 years

    My Webservice call to Mongo returns following JSON. I need to iterate this JSON value and remove the Item - product_language as it contain NULL/Empty string.

    ANy thoughts on how to do this?

    Python 3.4 version.

    {

    "prod_doc_key" : "613509",
    
    "metadata" : {
        "channel_availability_for" : {
            "description" : "Kiosk and Web",
            "id" : 0
        },
    
        "dd_sold_out_flag" : 0,
        "dd_units_sold_flag" : 0,
        "display_type_id" : {
            "id" : 0
        },
        "preorder_flag" : 0,
        "price_in_cart_flag" : 0,
        "product_language" : "",
        "product_type" : {
            "id" : 0,
            "name" : "Product"
        },
        "promotion_flag" : 0,
        "published" : 1,
        "rebate_flag" : 0
    
    
    }
    

    }