0

I am trying to parse a JSON file with the code below, but I am getting an error:

var fs = require('fs');
var sampleData = require("./sampleData.json");
var dataInArray = JSON.parse(sampleData.toString());

Here is the error:

$ node prog.js 

undefined:1
[object Object]
 ^
SyntaxError: Unexpected token o
    at Object.parse (native)
    at Object.<anonymous> (~/prog.js:3:24) //The line where I perform the JSON parsing

What am I doing wrong?

1
  • Does your json code have a valid syntax? Commented Mar 20, 2015 at 10:58

1 Answer 1

3

When you require json with node, it is already parsed for you. Just do

var sampleData = require("./sampleData.json");
console.log(Object.keys(sampleData));

and sampleData will be the object represented by the JSON.

See this question.

EDIT: Be conscious when you do this, cause your data might be cached and not reload if multiple require occurs in your app. (See node.js docs). If you change your data while the application is active, it might be better to use a regular readFile and JSON.parse to reload the data from scratch when you need it.

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

1 Comment

Well that's surprising. :-) I wouldn't have expected it to support straight JSON, but I suppose if it's eval'ing...

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.