0

I'm new to Json and node.js

I'm trying load my json file into a jsonobject using node.js. But I'm unable to do so.

I've created 2 files one is server.js and jsonresponse.json. I need to load the jsonresponse.json in json object created in server.js using javascript or node.js. This is snippet of server.js

var file = 'jsonresponse.json'
jsonfile.readFile(file, function(err, obj) {

       jsonObject = console.dir(obj);
 })
1
  • Whilst it is well worth looking into manually reading a file stream with the fs module and parsing it yourself. If you require() the json file node will read and parse it for you. The downside is if there was an error parsing or reading it will throw an exception. Commented Apr 26, 2016 at 7:00

3 Answers 3

3

suppose my json data is in myDirectry/data.json

//data.json
{
    "a":2,
    "b":3
}

So my myDirectory/app.js should be.

var x=require('./data');//or require('data');
console.log(x);

In order to read ,only require() is enough though u can read it using fs.But the best way is to require.

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

Comments

1

While the following code will give you the object in procedural way you should keep in mind the asynchronous behaviour of node.

   var jsonfile = require('jsonfile')
   var file = 'jsonresponse.json'
   var jsonObject = jsonfile.readFileSync(file)

As you are starting with node, you should get familiar with the callback pattern

In the snippet provided by you the file is being loaded in callback and you should be accessible within that scope.

   var file = 'jsonresponse.json';
   var jsonObject;
   jsonfile.readFile(file, function(err, obj) {
       //on success obj is the data therefore it holds the reference to contents of the file
       if(!err){
            jsonObject = obj;
       }
       else console.log(err);
   })

jsonfile.readFile is called withe the filename and a callback function. Once it completes the task of reading file it invokes the callback function with 2 parameters: error and data.

error is null if theres no problem, otherwise it contains the error details.

data contains whatever data the function wanted to return.

Comments

0

If you need to avoid caching (file changes between calls) do this

var fs = require('fs')
var obj = JSON.parse(fs.readFileSync('myfile.json').toString())

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.