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

Nimra Sajid
  • 41
  • 1
  • 1
  • 3

1 Answers1

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!

jaredready
  • 2,398
  • 4
  • 23
  • 50
  • 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. – Nimra Sajid May 15 '20 at 14:29
  • Oh right yeah `print` is being smart and formatting it for you, while `return`ing 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 https://stackoverflow.com/a/12944035/2887128. That looks like about what you need. – jaredready May 15 '20 at 14:40