1

I am getting an error that "directory is not defined" I really don't know if it means in my code or my json file. Here is the json file which I checked the format with https://jsonformatter.curiousconcept.com/

    [
    {
    "directory": "C:\\Users\\PCAdmin\\Downloads\\jsonin",
    "dirID": "dir01"
    },
    {
    "directory": "C:\\Users\\PCAdmin\\Downloads\\jsonout",
    "dirID": "dir02"
    }
    ]

Here is my code which based on examples I've seen should work yet I can't seem to get past the error;

    'use strict';
    var fs = require('fs'); 
    var jsonObj = require("./jsonDirectories.json");
    for(directory in jsonObj) {
      console.log("Dir: "+jsonObj.directory);
    }

I'm sure it's something stupid but any direction would be appreciated

NodeNewb
  • 49
  • 1
  • 4
  • Possible duplicate of [Loop through array in JavaScript](http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript) – dm03514 Dec 18 '15 at 19:51
  • Try this. console.log("Dir: "+directory.directory); . You might want to use good naming conventions here. – pratikpawar Dec 18 '15 at 19:58

3 Answers3

1

You need to declare the directory variable before using it:

for (let item of jsonObj) {
  // This line also needed fixing:
  console.log("Dir: ", item.directory);
}
robertklep
  • 198,204
  • 35
  • 394
  • 381
1

The error means that the variable directory on line 4 of your code was not initialized. The following code will fix that bug:

'use strict';
var fs = require('fs'); 
var jsonObj = require("./jsonDirectories.json");
for (var dirInfo in jsonObj) {
    console.log("Dir: " + dirInfo.directory);
}

However, this still does not do what you want, because the in operator does not work this way for arrays. The in operator is generally used to get the keys of objects (and then should still be used carefully).

To loop over your array of directory info, what you want is the following:

'use strict';
var fs = require('fs'); 
var jsonObj = require('./jsonDirectories.json');
jsonObj.forEach(function(dirInfo) {
    console.log('Dir: '+dirInfo.directory);
}

(I also removed the mixed single and double quotes, which is good practice.)

Joost Vunderink
  • 1,178
  • 6
  • 14
0

when you use for(directory in jsonObj) in node.js, directory will be assigned to the index of each of the items, not the value. so you can use jsonObj[directory] to get the directory.

But in my mind, this alternative is better:

jsonObj.forEach( function(directory) { 
  console.log("Dir: "+ directory);
});
Nir Levy
  • 12,750
  • 3
  • 21
  • 38