Home > Net >  Python Dictionary From Lambda Github Webhook Event Failing to Lookup Key Value
Python Dictionary From Lambda Github Webhook Event Failing to Lookup Key Value

Time:10-04

I have an AWS Lambda that is sitting behind a API Gateway and taking POST requests from GitHub on Pull Requests. I'm trying to process the Payload so that I can make decisions based on the Pull Request status.

My issue is that I'm not able to get the dictionary key value. This is a slimmed down version of the dictionary that I'm getting in the Event variable of the Lambda (the payload from GitHub):

dict = {'version': 2.0, 'routeKey': 'POST /', 'body': '{"action": "synchronize","number": 1,"pull_request": {"url":"https://myurl.com"}'}
print(dict['body']['action'])

I need to get the value of the pull_request url. I get the following when I try to process the dictionary:

print(dict['version'])  # 2.0
print(dict['body']['pull_request']['url'])  #TypeError: string indices must be integers

Why is there a single quote in the dictionary that is preventing me from accessing keys and values?

How can I get the value of the pull request url from this key?

CodePudding user response:

It is because dict['body'] is a string not a dictionary, you have to convert that to a dictionary before you can access.

Also it seems to be a malformed JSON string, missing a closing '}'

{"action": "synchronize","number": 1,"pull_request": {"url":"https://myurl.com"}

If you fix that you can then use json.loads

from json import loads

event = {'version': 2.0, 'routeKey': 'POST /', 'body': '{"action": "synchronize","number": 1,"pull_request": {"url":"https://myurl.com"}}'}

print(loads(event['body'])['pull_request']['url'])
  • Related