EpicTonic EpicTonic -4 years ago 156
Node.js Question

Reading from JSON returns undefined

I'm trying to read from a JSON that contains my error messages, so that in case I'd ever want to change what my error messages say, I'd just change the JSON instead of diving into my source code. Everything seems to be working fine...

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)


This is what's in 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."
}
]
}


When I log to the console,
errorMsgs
displays fine. When I log one of the items that
errorMsgs
has (like
bad_password
), it also works fine, as in it displays the items that are nested inside. However, when I attempt to retrieve a specific value like
errorMsgs.bad_password['error']
, it returns undefined. I can't seem to figure it out. I tried dot notation (
errorMsgs.bad_password.error
), which returns undefined. I tried the method above (
errorMsgs.bad_password['error']
) which also returns undefined. Asking for the
typeof
of
errorMsgs
, it returns
object
, which I assume makes it not a string. Passing the value to a variable first and then logging the variable doesn't do anything either. Is node converting it to a string on-the-fly, causing it to return undefined, or am I just doing something wrong?

Answer Source
bad_password" : [
    {
      "error" : "Incorrect login credentials.",
      "details" : "This happens if you either have an incorrect username or password. Please try again with different credentials."
    }
  ],

Your nested object is contained in an array.

errorMsgs.bad_password[0]['error']

This is what you're looking for. Just grab the first value of the array

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download