I'm trying to read an array of strings out of a JSON file, and I seem to be able to load in the JSON array but I'm failing to actually access the data within. My JSON file looks like:
{
"insults": [" string 1", " string 2", " string 3" ]
}
The javascript trying to read the array in the main.js file looks like:
var insults = require("./insults.json");
console.log(insults);
console.log(insults[0]);
The console returns the JSON array for the first log, but returns undefined when I try to call the specific location within the array. Is there some function I'm missing to read from the array, or am I missing some steps in between?
3 Answers 3
Try it like this: 'insults.insults'
var insults = {
"insults": [" string 1", " string 2", " string 3"]
};
console.log(insults.insults);
2 Comments
Insults is reading in as an object.
{
insults: [ ' string 1', ' string 2', ' string 3' ]
}
You need to either reference it as insults.insults[0] or import as var insults = require("./insults.json").insults;
Another option is to save your JSON as an array:
// insults.json
[
"string 1",
"string 2",
"string 3"
]
Comments
When parsing JSONs/objects you could always take the advantage of typeof and instanceof, to make sure what you are referencing exactly. In your case, not to interpret the first console.log the wrong way, you could test like this:
var insults = require("./insults.json");
console.log(insults instanceof Array); // false
console.log(typeof insults[0]); // undefined
// and then to double check:
console.log(insults.insults instanceof Array); // true
console.log(typeof insults.insults[0]); // string