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