I have a JSON file that I want to use in a Node.js script. I want to pass the json and then the script to parse it. I tried using fs.readFileSync(filename), but that returns a buffer. How can I convert that back to JSON so that I can parse it?
If you read it from a buffer, you can convert it with JSON.parse().
> var fs = require('fs');
undefined
> a=fs.readFileSync('a.json');
<Buffer 7b 0d 0a 20 20 20 20 22 67 6c 6f 73 73 61 72 79 22 ...>
> JSON.parse(a);
{ glossary:
{ title: 'example glossary',
GlossDiv: { title: 'S', GlossList: [Object] } } }
File must be a valid JSON.
You can also do require to directly load the JSON.
> var a=require('a.json');
undefined
> a
{ glossary:
{ title: 'example glossary',
GlossDiv: { title: 'S', GlossList: [Object] } } }
By default require checks inside node_modules folder inside current directory not the current folder. So you should give the path.