0

The data stored is in data.js file (not JSON) and it is an array of objects. As an example,

 [
    {"id":"u4cse101", "name":"supriya","batch":"b"},
    {"id":"u4cse102", "name":"rahul", "batch":"a"},
    {"id":"u4cse345", "name":"ahalya", "batch":"a"}
 ]

I tried many methods, but couldn't achieve. Your help will be appreciated. UPDATE: One solution found is have the following in data.js file

JOURNAL = [
  {"x":"y"},
  {"a":"a"}
];
if (typeof module != "undefined" && module.exports)
  module.exports = JOURNAL;

and use the variable JOURNAL in another javascript file directly using require('./data.js'). But I am getting error:

if (typeof module != "undefined" && module.exports)
^^

SyntaxError: Unexpected token if
3
  • var fs = require('fs'); var array = JSON.parse(fs.readFileSync('./data.js', 'utf8')); Commented Oct 20, 2016 at 5:12
  • Why not rename the file? JSON should be in data.json, not in data.js - the latter should be a JavaScript file, which JSON only technically is. Commented Oct 20, 2016 at 5:18
  • I neither want data.json file name or fs module. I have seen some code samples, they do it without these but I am not able to do it. Commented Oct 20, 2016 at 5:51

5 Answers 5

2

you can save your json data file as data.json and use require to import json file

var jsn = require("./data.json");
jsn = JSON.parse(jsn);

//data.json
[
{"x":"y"},
{"a":"a"}
];
Sign up to request clarification or add additional context in comments.

Comments

0

It's easy, you can follow this approach.

var fs = require('fs');
var obj;
fs.readFile('data.js', 'utf8', function (err, data) {
  if (err) throw err;
  obj = JSON.parse(data);
});

Hope it resolve your issue :)

Comments

0

You can use like this

var fs = require('fs');
fs.readFile('data.js', 'utf8', function(error, data) {
    data = JSON.parse(data);
})
//or
var data = fs.readFileSync('data.js', 'utf8');

Comments

0

I solved the problem. The file should be

JOURNAL = [[
  {"x":"y"},
  {"a":"a"}
]];

instead of

JOURNAL = [
  {"x":"y"},
  {"a":"a"}
];

Comments

0

data.json file

{
"firstname:"abc",
"lastname":"xyz"
}

And then your route.js file you can include data.json file and print the data value like that:

var fs = require('fs'), obj

// Read the file and send to the callback fucntion
fs.readFile('path of data.json file', fileHandler)

// Write the callback function

function fileHandler(err, data) {

    if (err) throw err
    obj = JSON.parse(data)
    // You can now play with your datas
}

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.