Felipe César
Felipe César

Reputation: 1444

How to parse POST array data in AWS Lambda

I'm trying to send JSON data with an array to an AWS Lambda function, but I can't parse the array.

In the frontend I'm requesting this way:

const ids = ['long_id1', 'long_id2', 'long_id3'];

const request = await fetch(
  'https://ID.execute-api.us-east-1.amazonaws.com/default/endpoint',
  {
    headers: {
      "accept": "application/json, text/plain, */*",
      "content-type": "application/json",
    },
    body: JSON.stringify({
      userIds: ids
    }),
    method: 'POST'
 }
)
const response = JSON.parse(await request.text());

In the lambda I have the following code:

exports.handler = async (event) => {
  const parsed = JSON.parse(event); //also tried: JSON.parse(JSON.stringify(event)) because I saw someone recommending it

  return {
    statusCode: 200,
    body: JSON.stringify(parsed)
  }

}

But I get event.body as a string. For example if I log the event variable I get:

event: {
  ...,
  body: "{\"userIds\":[\"long_id1\",\"long_id2\",\"long_id3\"]}"
}

But, if I try to parse the body, it throws this error:

ERROR   SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at Runtime.exports.handler (/var/task/index.js:11:23)
    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)
2021-08-08T07:43:05.425Z 5feeddb7-6254-405d-b311-42924abc5f4d ERROR SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) at Runtime.exports.handler (/var/task/index.js:11:23) at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)

Any idea what am I doing wrong?

Update

Not sure if was some kind of typo but now I'm able to get the data properly. I'm just doing what @Mark B said with the following code in the lambda function:

exports.handler = async (event) => {
  const { userIds } = JSON.parse(event.body);

  const result = await doSomethingWithUserIds(userIds)

  return {
    statusCode: 200,
    body: JSON.stringify(result)
  }

}

Thanks for all the help :)

Upvotes: 1

Views: 2635

Answers (2)

Mark B
Mark B

Reputation: 200456

event is an object. You don't need to parse that into JSON, it's already a JSON object. event.body is a string. You need to parse that property of the event object into JSON.

JSON.parse(event.body)

Upvotes: 1

Felipe C&#233;sar
Felipe C&#233;sar

Reputation: 1444

Not sure if was some kind of typo but now I'm able to get the data properly. I'm just doing what @Mark B said with the following code in the lambda function:

exports.handler = async (event) => {
  const { userIds } = JSON.parse(event.body);

  const result = await doSomethingWithUserIds(userIds)

  return {
    statusCode: 200,
    body: JSON.stringify(result)
  }

}

Thanks for all the help :)

Upvotes: 0

Related Questions