Im trying to replace python dictionary key with a different key name recursively for which i am using aws lambda with a api endpoint to trigger. Suprisingly the recursion part fails for weird reason. The same code works fine in local.
Checked cloudwatch logs. No error message get displayed there. Let me know if im missing anything here
EDIT: Related to Unable to invoke a recursive function with AWS Lambda and recursive lambda function never seems to run
### function that is called inside lambda_handler
def replace_recursive(data,mapping):
for dict1 in data:
for k,v in dict1.copy().items():
if isinstance(v,dict):
dict1[k] = replace_recursive([v], mapping)
try:
dict1[mapping['value'][mapping['key'].index(k)]] = dict1.pop(mapping['key'][mapping['key'].index(k)])
except KeyError:
continue
return data
## lambda handler
def lambda_handler(events,_):
resp = {'statusCode': 200}
parsed_events = json.loads(events['body'])
if parsed_events:
op = replace_recursive(parsed_events,schema)
resp['body'] = json.dumps(op)
return resp
Input I pass:
{
"name": "michael",
"age": 35,
"family": {
"name": "john",
"relation": "father"
}
}
In the output, keys in the nested dictionary are not getting updated. Only outer keys get modified
CodePudding user response:
Since you're ingesting JSON, you can do the key replacement right in the parse phase for a faster and simpler experience using the object_pairs_hook
argument to json.loads
.
import json
key_mapping = {
"name": "noot",
"age": "doot",
"relation": "root",
}
def lambda_handler(events, _):
replaced_events = json.loads(
events["body"],
object_pairs_hook=lambda pairs: dict(
(key_mapping.get(k, k), v) for k, v in pairs
),
)
return {
"statusCode": 200,
"body": json.dumps(replaced_events),
}
body = {
"name": "michael",
"age": 35,
"family": {"name": "john", "relation": "father"},
}
print(
lambda_handler(
{
"body": json.dumps(body),
},
None,
)
)
prints out
{'statusCode': 200, 'body': '{"noot": "michael", "doot": 35, "family": {"noot": "john", "root": "father"}}'}