简体   繁体   中英

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\\"}

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>

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM