Home > front end >  Unable to read specific JSON keys in my lambda function
Unable to read specific JSON keys in my lambda function

Time:02-07

Having this undefined issue in my node lambda function here is the code

exports.handler = async function (event, context) {
console.log('top')
console.log(event.body)
console.log(event.body.value)
console.log('bottom')

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

And here is a cloud watch screenshot

Screenshot

Im new to lambda and post requests so any help as to the value key is much appreciated

CodePudding user response:

The body property of a lambda handler's event parameter is in string format by default. If you use typeof to view the data type of the body, you'll get a return value of string:

console.log(typeof event.body);  # logs 'string'

To access the body property using object syntax, you have to parse it first using JSON.parse method:

let body = JSON.parse(event.body);

to avoid unexpected surprise from naughty consumers, you can use this function which I personally use on my projects:

/**
   * @function getJsonBody
   * @description Method used for retrieving the JSON body of HTTP requests.
   * @param {object} event Lambda event parameter.
   * @returns {object} JSON body of request payload.
   */
  getJsonBody(event) {
    if (event && event.body !== null && event.body !== undefined) {
      try {
        let body = JSON.parse(event.body);

        return body;
      } catch (err) {
        return null;
      }
    }

    return null;
  }
  •  Tags:  
  • Related