这是我的JSON对象:
var EVENT_ID = {
"Enable Popup Blocker": "Sol_EnablePopupBlocker_IE",
"Disable Script Debug": "Sol_DisableScriptDebugger_IE",
"Clear History": "Sol_ClearHistory_IE",
"Reset Settings": "Reset_InternetExplorer_Settings_SA",
"Profile Issue": "Fix_Outlook_Profile_SA",
"Send Receive": "Fix_Send_Receive_Errors_Outlook_SA",
"Search Issue": "Fix_Search_Outlook_SA"
};
我正在尝试通过键访问JSON对象值,该键具有如下所示的空格
var eventID = JSON.stringify(req.body.result.parameters.solution);
var aptEventName = EVENT_ID[eventID];
eventID
的值为"Profile Issue"
当我记录我的aptEventName
变量时,它会将值抛出为undefined
。谁能告诉我我要去哪里错了?
答案 0 :(得分:1)
一个可能的情况::当您再次对字符串值执行JSON.stringify()
时,可能会发生这种情况。这就是为什么它会抛出未定义的值的原因,所以请不要在此处使用不必要的JSON.stringify()
var response = "response"
JSON.stringify(response)
""response""
^^ ^^ see extra quotes here
var result = { "source": "agent", "resolvedQuery": "LPTP-KDUSHYANT", "speech": "", "action": "gethostname", "actionIncomplete": false, "parameters": { "solution": "Profile Issue", "hostname": "LPTP-KDUSHYANT" }}
var eventID = result.parameters.solution;
var EVENT_ID = {
"Enable Popup Blocker": "Sol_EnablePopupBlocker_IE",
"Disable Script Debug": "Sol_DisableScriptDebugger_IE",
"Clear History": "Sol_ClearHistory_IE",
"Reset Settings": "Reset_InternetExplorer_Settings_SA",
"Profile Issue": "Fix_Outlook_Profile_SA",
"Send Receive": "Fix_Send_Receive_Errors_Outlook_SA",
"Search Issue": "Fix_Search_Outlook_SA"
};
var aptEventName = EVENT_ID[eventID];
console.log(aptEventName)
答案 1 :(得分:1)
JSON.stringify
会返回该字符串,并用引号引起来。您不应该对密钥进行JSON编码。并且由于字符串类型转换在执行对象字段访问时是隐式的,因此可以将其键入为:
var eventID = req.body.result.parameters.solution;
var aptEventName = EVENT_ID[eventID];
答案 2 :(得分:1)
您不应该使用stringify,它使用一个字符串并将该字符串转换为JSON。
var eventID = JSON.stringify(req.body.result.parameters.solution);
执行此操作时,您的字符串将变为
var eventID = "\"Profile Issue\"";
因此,您在对象中当然没有带引号的属性。因此,您需要做的就是删除字符串化位,而只需引用对象中的属性即可。
var eventID = req.body.result.parameters.solution;
var aptEventName = EVENT_ID[eventID];
答案 3 :(得分:0)
您可以使用以下方法获取值:
EVENT_ID["Clear History"]
我认为您有些不满意
req.body.result.parameters.solution
。