Virtue Crazy Virtue Crazy - 5 months ago 10
JSON Question

Iterate through every key value in JSON dictionary in Python

I have a JSON string:

{"emailId":[],"Age":[],"siblings":[],"addedGroupIds":[],"role":{"name":"x","description":"y","Permissions":[],"clientId":102}}


I want to replace value from every key-value pair(unless the value itself is a dictionary,eg:"role"). I converted the above mentioned string to a dictionary in somerandomFunc() and then sent this dictionary to iterator(). Iterator() will recursively check if the value in each key-value pair is a dictionary or not. If the value is not a dictionary, it will send the key to smartScanner() where I will be replacing the value of the recieved key with myTestString

def somerandomfunc(self,JSONString):
payload=simplejson.loads(JSONString)
self.payload=payload
iterator(payload)

def iterator(self,payload):
for i in payload:
if isinstance(payload[i],dict):
self.iterator(payload[i])
else:
self.smartScanner(i)

def smartScanner(self,i):
mytestString='">qqqq'
if (self.payload.has_key(i)):
self.payload[i]=mytestString
print "%s:%s"%(i,self.payload.has_key(i))


I get the following output:

existingGroupIds:True
existingUserIds:True
assetPermissions:False
name:False
clientId:False
description:False
removedGroupIds:True
removedUserIds:True
addedGroupIds:True
addedUserIds:True


Which means that if statement in smartScanner() failed for keys "assetPermissions","name","clientId" and "description". And I wasn't able to replace the values of these keys with myteststring. I can understand the reason it failed was because it tried to access payload["name"] instead of payload["role"]["name"]

How do I change my logic so that I be able to replace the values even for keys "assetPermissions","name","clientId" and "description"? And that my program does not break no matter any hierarchies of dictionary are present in the JSON payload

Answer

I believe you are over-complicating it with your "smartscanner" function. Here is an approach, not using a class, but you should be able to convert it to a class method easily:

In [16]: example = {"emailId":[],"Age":[],"siblings":[],"addedGroupIds":[],"role":{"name":"x","description":"y","Permissions":[],"clientId":102}}

In [17]: def iterator(payload):
    ...:     for i in payload:
    ...:         if isinstance(payload[i],dict):
    ...:             iterator(payload[i])
    ...:         else:
    ...:             payload[i] = '">qqqq'
    ...:             

In [18]: iterator(example)

In [19]: example
Out[19]: 
{'Age': '">qqqq',
 'addedGroupIds': '">qqqq',
 'emailId': '">qqqq',
 'role': {'Permissions': '">qqqq',
  'clientId': '">qqqq',
  'description': '">qqqq',
  'name': '">qqqq'},
 'siblings': '">qqqq'}
Comments