Calling AWS Lambda from Lambda error – string indices must be integers

Total
17
Shares

I have the following code which calls a Lambda function from within a Lambda function, but I am having an issue with JSON parsing apparently:

import boto3
import json
import base64
client = boto3.client('lambda')
d = """{'body': {'jwttoken': 'eyJraWQiOiJxNm56YVhrbWxFYytmUDdwQ3hESDIxTUhQSU9KUGVyMUFKaW5aWTVJK3BNPSIsImFsZyI6IlJTMjU2In0.eyJzdWIi4cCI6MTYyMTU1NTQ0MiwiaWF0IjoxNjIxNTUxODQyLCJqdGkiOiIxYmZkYWFmMS00NmMxLTRiMTUtOTYxZC03NmQwZGVkMjIyMWMiLCJjbGllEGeCsJ0BrFAsmzWK18t9JIAYzVG4-4f0nEG-TCXrjkGOHUJCnSQ2KHXs7wK0xi4bpDkuDkyz45A7u29BkXsE6-mrSfks4OQH9jFYtwstbaA', 'message': 'test message'}}"""
s = {}
s['statusCode'] = 200
s['body'] = json.dumps(d)
response = client.invoke(
    FunctionName='arn:aws:lambda:us-east-2:XXXXXXXXX',
    LogType='None',
    Payload=json.dumps(d)
)
print(json.loads(response.get('Payload').read()))

{'errorMessage': 'string indices must be integers', 'errorType': 'TypeError', 'stackTrace': ['  File "/var/task/app.py", line 29, in lambda_handlern    Body = json.loads(event['body'])n']}

The relevant Lambda handler code:

Body = json.loads(event['body'])
token = Body['jwttoken']
message = Body['message']

Any thoughts would be greatly appreciated!


Solution

Your input json string d is invalid json (json does not use single quotes). If you want to keep using d as it is, you can’t treat it as json.

Instead you should use ast to get your token and message:

import ast

Body = ast.literal_eval(event)['body']
token = Body['jwttoken']
message = Body['message']
Leave a Reply

Your email address will not be published. Required fields are marked *