0

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

2

Try it like this: 'insults.insults'

var insults = {
    "insults": [" string 1", " string 2", " string 3"]
};

console.log(insults.insults);

Sign up to request clarification or add additional context in comments.

2 Comments

That was it! Thanks for the help :)
Glad I could help, happy coding!
1

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

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.