Search code examples
node.jsamazon-web-servicesaws-lambdaaws-api-gateway

AWS lambda body object can't be mapped(values can't be accessed)


I am using AWS lambda with API gateway. I can access the body inside event object using dot notation. Here is the schema of body

{
  "items": {
    "1681393109842MIN:01GXX9JHKHP5ZDW92NRRNPBHA4": {
      "name": "Chicken Tandoori",
      "price": 300,
      "qty": 2
    },
    "1681399155580MIN:01GXX9JHKHP5ZDW92NRRNPBHA4": {
      "name": "Mutton Tandoori",
      "price": 400,
      "qty": 2
    }
  },
  "message": "This is a dummy message"
}

event.body provides access to the body object but after that I cannot access the values using dot operator or anything.

What have I tried:

  • Using square brackets with key to access data.
  • Deepcopying the object

Solution

  • In the case of Lambda Proxy Integration, you receive a JSON string in event.body, therefore you need to parse it like so:

    const data = JSON.parse(event.body);
    console.log(data.message); // now you can access it using dot notation.
    

    This can be seen in the official AWS Lambda Tutorial:

    if (event.body) {
        let body = JSON.parse(event.body)
        ...
        ...
    }