Reputation: 1174
I am trying to send a file via AWS Lambda but it's returning error(TypeError(repr(o) + " is not JSON serializable")
).
I tried by encoding a zip file and send it along with the response. But it's returning error.
Here is my sample code:
import json
import base64
import zipfile
def lambda_handler(event, context):
# TODO implement
archive_name = '/tmp/test_file.zip'
with zipfile.ZipFile(archive_name, 'w') as zip_file:
pass
zip_file.close()
image_processed = open(archive_name, 'rb')
image_processed_data = image_processed.read()
image_processed.close()
res = base64.encodestring(image_processed_data)
return{
'statusCode': 200,
'body': res,
'headers': {
'Content-Type': 'application/octet-stream',
},
'isBase64Encoded': True
}
Response:
{
"errorMessage": "b'UEsDBBQAAAAAAEhAbU/8RgkRDgAAAA4AAAAJAAAAdG1wL2EudHh0S2FydGhpa2V5YW4gS1JQSwEC\\nFAMUAAAAAABIQG1P/EYJEQ4AAAAOAAAACQAAAAAAAAAAAAAAtIEAAAAAdG1wL2EudHh0UEsFBgAA\\nAAABAAEANwAAADUAAAAAAA==\\n' is not JSON serializable",
"errorType": "TypeError",
"stackTrace": [
[
"/var/lang/lib/python3.6/json/__init__.py",
238,
"dumps",
"**kw).encode(obj)"
],
[
"/var/lang/lib/python3.6/json/encoder.py",
199,
"encode",
"chunks = self.iterencode(o, _one_shot=True)"
],
[
"/var/lang/lib/python3.6/json/encoder.py",
257,
"iterencode",
"return _iterencode(o, 0)"
],
[
"/var/runtime/awslambda/bootstrap.py",
134,
"decimal_serializer",
"raise TypeError(repr(o) + \" is not JSON serializable\")"
]
]
}
I attached the sample code which I tried and also added the error response from the Lambda.
Thanks in advance.
Upvotes: 0
Views: 1890
Reputation: 774
The type of res
is bytes
, so it's not Json serializable.
You could try:
return{
'statusCode': 200,
'body': res.decode(),
'headers': {
'Content-Type': 'application/octet-stream',
},
'isBase64Encoded': True
}
Upvotes: 0