9

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


}

}

codeforester
  • 39,467
  • 16
  • 112
  • 140
user3092876
  • 103
  • 1
  • 1
  • 3
  • Similar issue is resolved in these threads. http://stackoverflow.com/questions/19201233/how-to-delete-json-object-using-python http://stackoverflow.com/questions/28706841/remove-python-dict-item-from-nested-json-file – TheWayYouSeeIt Dec 08 '15 at 22:28

3 Answers3

5

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.

Ali Nikneshan
  • 3,500
  • 27
  • 39
1

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
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
0

You can remove a key k from a dictionary d with the syntax:

del d[k]
6c1
  • 392
  • 2
  • 14