0

I read in a file from S3 bucket using Python:

import json
import boto3


 s3 = boto3.client('s3')

def lambda_handler(event, context):

 bucket =  'finalyearpro-aws'
 key = 'StudentResults.json'


 try:
     data = s3.get_object(Bucket=bucket, Key=key)
    json_data = data['Body'].read().decode('utf-8')

    print (json_data)

except Exception as e:

    raise e

But it does not display in the response, instead it creates it as function logs, how do I display it in the response instead. See Picture Below.

Lambda Function Python Read File Response - Click Here

1 Answer 1

1

AWS Lambda sends all console output to CloudWatch so you can view it. Since you can't hook into the process running your Lambda you'd otherwise have no way of viewing your Lambda logs.

If you want to return this JSON as a response from your Lambda then you just need to return that value. You can find information about the Lambda handler in Python here.

An example of what you're looking to do would be the following (your code with the uninteresting bits removed for brevity):

def lambda_handler(event, context):

 bucket =  'finalyearpro-aws'
 key = 'StudentResults.json'

 data = s3.get_object(Bucket=bucket, Key=key)
 json_data = data['Body'].read().decode('utf-8')

 return json_data

I hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Jared, that is the way I had it first actually but it displays the JSON file without any indentations and that is why I changed it to print instead of return. Any idea how to make the JSON file indented the way it should be instead of reading as one continuous line. Thanks.
Oh right yeah print is being smart and formatting it for you, while returning the value it's just a plain old string. I'm not a Python expert but you can probably do something like return json.dumps(json_data, indent=4) Pretty printing JSON is really a different question, but you can start here stackoverflow.com/a/12944035/2887128. That looks like about what you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.