I've been having trouble converting a .json file into an array object in NodeJS,
This is my JSON:
{
"cat": {
"nani": "meow"
},
"dog": {
"nani": "woof"
}
}
index.js:
const array = require('../../data/usershops.json');
var shop = array[0].nani
return shop;
The output in console is:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'nani' of undefined
It actually returns a value if I used this:
array["cat"].nani // => "meow"
How can I get the index key?
JSON.parse()to get the data structure then process it as you need.const array = require('../../data/usershops.json');--require()knows how to parse JSON files and it gets you back an object. There isn't any array here. Consequently attempting to getarray[0]produces an error. UseObject.values()to extract only the values from an object. It ignores the keys and returns the array you need.