0

How to remove all the Keys under all elements that have a value 'NONE', so in this example busCode, effectivedate and col1. Sample Json and the python code that I tried are pasted here

  {
  "colo": {
  "TrBus":{
   "trade": "Test999", 
   "busCode": "NONE",
   "Trtype": "XXX",
   "sortOrder": "78654",
   "effectivedate": "NONE",
   "expirationdate": "31-DEC-9999"
  } 
  "TrCol":{
    "Col1": "NONE",
    "Col2": "Conf"
   }     }
  }

I started off with this but doesn't work as expected

 def constructJson(jsonstr):
 jdata = json.load(jsonstr)
 for key, value in jsonstr:
   if value == 'NULL':
     del key
 return jdada
3
  • 1
    1. for key, value in jsonstr: should be for key, value in jdata: 2. del key should be del jdata[key] and 3. this is not recursive (meaning, it doesn't handle nested values) Commented Feb 23, 2019 at 0:13
  • This question is very similar to yours. You can just replace is not None with != "NONE" in the accepted answer and then return remove_none(jdata) will work. Commented Feb 23, 2019 at 0:22
  • This solution worked. Thanks Boris Commented Feb 23, 2019 at 1:47

2 Answers 2

1

This solution creates a recursive function to iterate over the dict and remove the 'NONE's:

def del_none(obj):
    for key, value in obj.copy().items():
        if isinstance(obj[key], dict):
            obj[key] = del_none(obj[key])
        else:
            if value == 'NONE':
                del obj[key]
    return obj

Defining the original dictionary as:

original_dict = { "colo": {
  "TrBus":{
   "trade": "Test999", 
   "busCode": "NONE",
   "Trtype": "XXX",
   "sortOrder": "78654",
   "effectivedate": "NONE",
   "expirationdate": "31-DEC-9999"
  }, 
  "TrCol":{
    "Col1": "NONE",
    "Col2": "Conf"
   }
  } 
  }

And calling the function:

new_dict = del_none(original_dict)

It produces the following output:

new_dict
{'colo': {'TrBus': {'Trtype': 'XXX',
   'expirationdate': '31-DEC-9999',
   'sortOrder': '78654',
   'trade': 'Test999'},
  'TrCol': {'Col2': 'Conf'}}}
Sign up to request clarification or add additional context in comments.

5 Comments

Your function doesn't return a new dict - it modifies the original in-place.
Indeed, I wasn't updating the element on the recursive call. Thanks for pointing this out, @ekhumoro.
Thank you Daniel, this solution also worked.
Is there a way to update a 'testvalue' anywhere in the nested JSON structure to a 'newvalue' without knowing the Key PATH?
You can add this following code in the else condition: if value == 'testvalue': obj[key] = 'newvalue'
-1

Try:

def constructJson(jsonstr):
  jsondata = json.load(jsonstr)
  for key, value in jsondata:
    if value == 'NULL':
      del jsondata[key]
  return jsondata

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.