bangali babu
bangali babu

Reputation: 127

Convert string which is read from a file to json object in nodejs

I am reading a string from a file and want to convert it into a json object File content: {name:"sda"}

Code:

var fs=require('fs');

var dir='./folder/';
fs.readdir(dir,function(err,files){
    if (err) throw err;

    files.forEach(function(file){


        fs.readFile(dir+file,'utf-8',function(err,jsonData){
            if (err) throw err;
            var content=jsonData;
            var data=JSON.stringify(content);
            console.log(data);
        });

    });

But I am getting this output: {name:\"sda\"}

Upvotes: 2

Views: 6129

Answers (2)

chridam
chridam

Reputation: 103345

In addition to JSON.stringify() method which converts a JavaScript value to a JSON string, you can also use JSON.parse() method which parses a string as JSON:

fs.readFile(dir+file,'utf-8',function(err, jsonData){
    if (err) throw err;    
    var content = JSON.stringify(jsonData);
    console.log(content);

    var data = JSON.parse(content);
    console.log(data);

});

Check the demo below.

var jsonData = '{name:"sda"}',
    content = JSON.stringify(jsonData),
    data = JSON.parse(content);

pre.innerHTML = JSON.stringify(data, null, 4);
<pre id="pre"></pre>

Upvotes: 1

Shanoor
Shanoor

Reputation: 13662

Since your file is not a valid JSON, you can use eval (it's a dirty hack but it works), example :

data = '{name:"sda"}';
eval('foo = ' + data);
console.log(foo);

Upvotes: 1

Related Questions