2

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

can't use eval can u give me any other way
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
1

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

2 Comments

cant do JSON.parse because it is not in json format When i am doing that i am getting this error:- Unexpected token name
In that case use a combination of the two methods, I've updated my answer to reflect this.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.