Reputation: 2279
I an getting aws event parameter as follow in the lambda call.
let event = { pathParameters: '{"foo":"35314"}' }
When I am trying to validate the parameter in condition , it cant find foo
key on pathParameters
Here my condition check
if (event.pathParameters && event.pathParameters.foo) {
//do something
} else {
console.log('fail');
}
It going in else
condition . I tried JSON.parse(JSON.strinify(event))
. It did not help. I do get the Object if I do JSON.parse(event.pathParameters)
.
Any way to resolve the issue on root level object.
Upvotes: 1
Views: 703
Reputation: 87262
No, you can't parse the event
to get access to the '{"foo": "35314}'"
, you need to parse the event.pathParameters
value to get the actual foo
and its value, 35314
let event = { pathParameters: '{"foo":"35314"}' }
if (event.pathParameters && JSON.parse(event.pathParameters).foo) {
console.log("'foo' =", JSON.parse(event.pathParameters).foo);
} else {
console.log('fail');
}
Upvotes: 3
Reputation: 10148
This is because the data that you are getting has JSON as stringified in pathParameters
, so you'll have to parse with that key something like
JSON.parse(event.pathParameters).foo
Upvotes: 1
Reputation: 1523
function doSomething(event) {
let pathParametersObj = JSON.parse(event.pathParameters);
if (pathParametersObj && pathParametersObj.foo) {
//do something
console.log('pass');
} else {
console.log('fail');
}
}
let event1 = {
pathParameters: '{"foo":"35314"}'
}
let event2 = {
pathParameters: null
}
doSomething(event1);
doSomething(event2);
Upvotes: 0
Reputation: 146350
let event = { pathParameters: '{"foo":"35314"}' } // foo is a string
if (event.pathParameters) {
try {
const { foo } = JSON.parse(event.pathParameters);
// use foo
} catch (jsonError) {
console.log('There was some json parse error', jsonError);
}
} else {
console.log('fail');
}
You need to parse the data from event.pathParameters
Upvotes: 0