Solve Could not Parse Request body into JSON Error - AWS CLI

avatar

Borislav Hadzhiev

Fri Sep 17 20212 min read

Solve Could not Parse Request body into JSON Error #

The "InvalidRequestContentException - Could not Parse Request body into JSON Error" error occurs when invoking a lambda function with syntactically incorrect JSON payload, or forgetting to set the --cli-binary-format parameter to raw-in-base64-out.

For example the following command throws the error:

shell
aws lambda invoke --function-name testFunction --cli-binary-format raw-in-base64-out --payload '{"name": "John Doe",}' response.json

could not parse request body

The reason is the dangling comma in the --payload parameter.

Note that if you're on Windows, you should escape the double quotes in the JSON string - '{\"name\": \"John Doe\"}'.

The fastest way to validate and correct your JSON is to use a JSON validator.

Paste your payload into the form, the validator checks for errors and sometimes directly fixes them.

The --payload parameter expects base64 encoded input by default, so when passing a raw json string, we have to set the --cli-binary-format parameter to raw-in-base64-out.

Once I correct the JSON string and remove the dangling comma, the invoke command executes successfully:

shell
aws lambda invoke --function-name testFunction --cli-binary-format raw-in-base64-out --payload '{"name": "John Doe"}' response.json

successful invocation

Similarly, if we invoke the lambda function with syntactically incorrect JSON stored in a file, we still get the "Could not parse request body into json" error.

shell
aws lambda invoke --function-name testFunction --cli-binary-format raw-in-base64-out --payload file://event.json response.json

file payload could not parse error

The contents of the file supplied to the --payload parameter can be any JSON with syntax errors, i.e.:

event.json
{ 'name': 'John Doe' }

In this case enclosing the key and value in double, instead of single quotes solves the error.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee