[英]parse JSON object with value passed as single quote string
I an getting aws event parameter as follow in the lambda call. 我在lambda调用中获得了一个aws事件参数,如下所示。 let event = { pathParameters: '{"foo":"35314"}' }
When I am trying to validate the parameter in condition , it cant find foo
key on pathParameters
当我尝试验证condition中的参数时,无法在pathParameters
上找到foo
键
Here my condition check 这是我的病情检查
if (event.pathParameters && event.pathParameters.foo) {
//do something
} else {
console.log('fail');
}
It going in else
condition . 它在else
条件下进行。 I tried JSON.parse(JSON.strinify(event))
. 我尝试了JSON.parse(JSON.strinify(event))
。 It did not help. 它没有帮助。 I do get the Object if I do JSON.parse(event.pathParameters)
. 如果我执行JSON.parse(event.pathParameters)
我会得到对象。 Any way to resolve the issue on root level object. 解决根级对象问题的任何方法。
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
不,您无法解析 event
以访问'{"foo": "35314}'"
,您需要解析event.pathParameters
值以获取实际的foo
及其值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'); }
这是因为要获取的数据具有pathParameters
字符串化的JSON,因此您必须使用该键进行解析,例如
JSON.parse(event.pathParameters).foo
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
您需要从event.pathParameters
解析数据
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.