![](/img/trans.png)
[英]Not able to parse json string in ejs becuase of single quote in value
[英]parse JSON object with value passed as single quote string
我在lambda調用中獲得了一個aws事件參數,如下所示。 let event = { pathParameters: '{"foo":"35314"}' }
當我嘗試驗證condition中的參數時,無法在pathParameters
上找到foo
鍵
這是我的病情檢查
if (event.pathParameters && event.pathParameters.foo) {
//do something
} else {
console.log('fail');
}
它在else
條件下進行。 我嘗試了JSON.parse(JSON.strinify(event))
。 它沒有幫助。 如果我執行JSON.parse(event.pathParameters)
我會得到對象。 解決根級對象問題的任何方法。
不,您無法解析 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');
}
您需要從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.