Reputation: 107
Hello Everyone, I have trouble with fetching items from local json file as value and key in NodeJs.
[
{
"question":"What is the first name of your best friend in high school?",
"answer":"U2FsdGVkX18/l/UF1DbqMp9ItOqgmmQIeVUlxqrb7vE="},
{
"question":"What was your childhood nickname?",
"answer":"U2FsdGVkX1+x14bgpnjr3UcvScBDbIOnP55vua2NvME="},
{
"question":"What is the name of the street you grew up in?",
"answer":"U2FsdGVkX1+pGkO/MRIP7oHym3Ynz/7n/fYuEt7fTFw="}]
This the local json file. How can i fetch questions and answers and save them to different arrays. Thanks in advance.
Upvotes: 0
Views: 3639
Reputation: 3111
var data = [
{
"question":"What is the first name of your best friend in high school?",
"answer":"U2FsdGVkX18/l/UF1DbqMp9ItOqgmmQIeVUlxqrb7vE="},
{
"question":"What was your childhood nickname?",
"answer":"U2FsdGVkX1+x14bgpnjr3UcvScBDbIOnP55vua2NvME="},
{
"question":"What is the name of the street you grew up in?",
"answer":"U2FsdGVkX1+pGkO/MRIP7oHym3Ynz/7n/fYuEt7fTFw="
}];
var data = JSON.parse(data);
var questions = data.map(current => current.question);
var answers = data.map(current => current.answer);
Upvotes: 1
Reputation: 560
If your json file wants to be read from the file system it would be:
var fs = require('fs');
fs.readFile('./file.json', 'utf-8', (err, data) => {
if (err) throw err;
console.log(JSON.parse(data));
});
Upvotes: 0
Reputation: 9579
Assuming your local data file in data.json
, you can use it like shown below.
var data = require('./data.json')
console.log(data[0]);
Upvotes: 3