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\"}
Adriaan
18.2k7 gold badges48 silver badges88 bronze badges
asked Sep 29, 2015 at 12:12
bangali babu
1271 gold badge2 silver badges9 bronze badges
2 Answers 2
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);
answered Sep 29, 2015 at 13:06
Shanoor
13.7k2 gold badges32 silver badges41 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
bangali babu
can't use eval can u give me any other way
Shanoor
I'm curious, why can't you use eval? It's the quickest way, the other way implies to parse your invalid "json" and build an object from it. Something like that: jsbin.com/xexohejuzu/edit?js,output
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>
answered Sep 29, 2015 at 12:37
chridam
104k26 gold badges246 silver badges243 bronze badges
2 Comments
bangali babu
cant do JSON.parse because it is not in json format When i am doing that i am getting this error:- Unexpected token name
chridam
In that case use a combination of the two methods, I've updated my answer to reflect this.
lang-js