Home > other >  JSON parsing of event parameter in AWS Lambda extracts undefined
JSON parsing of event parameter in AWS Lambda extracts undefined

Time:06-05

This was working, and suddenly fails on extracting the "event.body" JSON object passed into this AWS Lambda nodeJS function:

exports.handler = function (event, context, callback) {

  console.log('Event: '   JSON.stringify(event));
  console.log('Event.Body: '   event.body);
  //console.log('Parsed Event: '   JSON.parse(event));
  let body = event.body;
  console.log('Body: '   body);
  const tgQueryName = body.queryName;
  const tgQueryParams = body.queryParams;
  console.log('tgQueryName: '   tgQueryName);
  console.log('tgQueryParams: '   tgQueryParams);

...

Both tgQueryName and tgQueryParams are 'undefined' - see CloudWatch log:

INFO Event: {"version":"2.0","routeKey":"POST /tg-query","rawPath":"/dev/tg-query","rawQueryString":"","headers":{"accept":"application/json, text/plain, */*","accept-encoding":"gzip, deflate","accept-language":"he-IL,he;q=0.9,en-US;q=0.8,en;q=0.7","cache-control":"no-cache","content-length":"51","content-type":"application/json; charset=UTF-8","host":"p6ilp2ts0g.execute-api.us-east-1.amazonaws.com","origin":"http://localhost","referer":"http://localhost/","sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"cross-site","user-agent":"Mozilla/5.0 (Linux; Android 11; Redmi Note 8 Build/RKQ1.201004.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/101.0.4951.61 Mobile Safari/537.36","x-amzn-trace-id":"Root=1-629b960c-072e8fa475ad26f56893c6f9","x-forwarded-for":"89.139.32.60","x-forwarded-port":"443","x-forwarded-proto":"https","x-requested-with":"com.skillblaster.simplify.dev"},"requestContext":{"accountId":"140360121027","apiId":"p6ilp2ts0g","domainName":"p6ilp2ts0g.execute-api.us-east-1.amazonaws.com","domainPrefix":"p6ilp2ts0g","http":{"method":"POST","path":"/dev/tg-query","protocol":"HTTP/1.1","sourceIp":"89.139.32.60","userAgent":"Mozilla/5.0 (Linux; Android 11; Redmi Note 8 Build/RKQ1.201004.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/101.0.4951.61 Mobile Safari/537.36"},"requestId":"TNRh_gq-oAMESEw=","routeKey":"POST /tg-query","stage":"dev","time":"04/Jun/2022:17:27:40  0000","timeEpoch":1654363660597},"body":"{\"queryName\":\"getActiveCountries\",\"queryParams\":{}}","isBase64Encoded":false}

INFO Event.Body: {"queryName":"getActiveCountries","queryParams":{}}

INFO Body: {"queryName":"getActiveCountries","queryParams":{}}

INFO tgQueryName: undefined

INFO tgQueryParams: undefined

I also tried: body["queryName"] - same result.

What am I missing?

CodePudding user response:

Your body content is a string and you need to JSON.parse it:

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

It was only clear when I stuck your initial event JSON into a JSON beautifier and it was a little clearer.

  • Related