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?

Eric Baldwin
  • 3,341
  • 10
  • 31
  • 71

1 Answers1

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.

Community
  • 1
  • 1
Pierrickouw
  • 4,644
  • 1
  • 30
  • 29
  • Well that's surprising. :-) I wouldn't have expected it to support straight JSON, but I suppose if it's `eval`'ing... – T.J. Crowder Mar 20 '15 at 11:05