我正在尝试从包含错误消息的JSON中读取内容,以便万一我想更改错误消息中的内容时,我只需更改JSON即可,而不必深入研究源代码。一切似乎都很好...
var fs = require('fs')
console.log("Now reading from error messages configuration file...");
var errorMsgs = JSON.parse(fs.readFileSync('config/error_msgs.JSON'));
console.log(errorMsgs)
这是errorMsgs.json中的内容:
{
"bad_password" : [
{
"error" : "Incorrect login credentials.",
"details" : "This happens if you either have an incorrect username or password. Please try again with different credentials."
}
],
"missing_fields" : [
{
"error" : "Credentials failed to parse.",
"details" : "This happens when one or more fields are missing (or have illegal characters in them), please try again with different credentials."
}
]
}
当我登录到控制台时,
errorMsgs
显示正常。当我记录errorMsgs
具有的项目之一(如bad_password
)时,它也可以正常工作,因为它显示了嵌套在其中的项目。但是,当我尝试检索诸如errorMsgs.bad_password['error']
之类的特定值时,它返回未定义。我似乎无法弄清楚。我尝试了点符号(errorMsgs.bad_password.error
),该符号返回未定义。我尝试了上述方法(errorMsgs.bad_password['error']
),该方法也返回未定义。要求typeof
的errorMsgs
,它返回object
,我认为它不是字符串。先将值传递给变量,然后再记录变量也无济于事。节点是在即时将其转换为字符串,导致其返回未定义的,还是我做错了什么? 最佳答案
bad_password" : [
{
"error" : "Incorrect login credentials.",
"details" : "This happens if you either have an incorrect username or password. Please try again with different credentials."
}
],
您的嵌套对象包含在数组中。
这就是您要寻找的。只需获取数组的第一个值