I am by no means a Python Guru, but I know my way around. For the past two hours however I've been banging my head against the following:
I am parsing a JSON response from a WCF Webservice using the json.loads() function. The result is a Python dictionary which I am using throughout my application. However, I now have the need to obfuscate the id, reseller_id etc. for use in HTTP GET requests.
This is an example of a response: (note, I have many of these responses, so I am looking for a generic solution.) I want to replace the value of any id with a hash of the id value
{
"token":"String content",
"user":{
"distributor":{
"email":"String content",
"id":2147483647,
"name":"String content"
},
"email":"String content",
"first_name":"String content",
"id":2147483647,
"last_name":"String content",
"reseller":{
"email":"String content",
"id":2147483647,
"name":"String content",
"portal_css":"String content",
"portal_logo":"String content",
"portal_name":"String content",
"portal_url":"String content"
},
"role":2147483647
}
}
I have tried all kinds of strategies using code like:
result = json.loads(json_result, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
and
def fun(d):
if 'id' in d:
yield d['id']
for k in d:
if isinstance(d[k], list):
for i in d[k]:
for j in fun(i):
yield j
I can't get it to work properly. So:
Question 1: Can I convert json to (Anonymous) Python Objects and how?
Question 2: Can I edit the resulting dict in place?
Question 3: When all else fails; Does anybody have an idea how to achieve this?
Thanks a lot!