Mandrek
Mandrek

Reputation: 1211

JSONDecodeError: Expecting value: line 1 column 1 error in AWS Lambda

I am trying to write a aws lambda function which will push the SQS queue output in a s3 bucket. But the lambda function is failing to push the message , the cloudwatch log is showing

JSONDecodeError: Expecting value: line 1 column 1

i am posting the lambda function which i am using

import json
import boto3

def lambda_handler(event, context):
s3 = boto3.client("s3")
data = json.loads(event["Records"][0]["body"]) --getting error in this line 
print(data)
s3.put_object(Bucket="sqsmybucket",key="data.json", Body=json.dumps(data))
#print(event)
return {
    'statusCode': 200,
    'body': json.dumps('Hello from Lambda!') 
}

The cloud watch log is showing

2020-05-30T23:51:45.276+05:30

[ERROR] JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 6, in lambda_handler
data = json.loads(event["Records"][0]["body"])
 File "/var/lang/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/var/lang/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/var/lang/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None

I have formatted the message and saved it to the cloud below is the link

[formatted JSON code][1]

formatted JSON

Please help , thanks in advance

Upvotes: 1

Views: 6478

Answers (1)

Marcin
Marcin

Reputation: 238747

Your event["Records"][0]["body"] is a plain string, not json:

"body": "A difficult message."

Therefore, json.loads(event["Records"][0]["body"]) is equivalent to json.loads("A difficult message.") which obviously fails.

To get body's value you can do the following instead:

data = event["Records"][0]["body"]

However, since later you have the following statment:

Body=json.dumps(data)

The Body will be:

Body='"A difficult message."'

which may or may not be what you desire.

Upvotes: 1

Related Questions