0
votes

So, I'm trying to read a json file and access the attributes that were written in the file.

The file is:

{ 'name': 'SpectrumApp', 'version': '0.1.0a', 'description': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam a lectus quis odio semper suscipit. Duis ac placerat mauris, vitae lacinia orci. Fusce ultrices enim ligula, in suscipit arcu volutpat a. Proin posuere aliquam consequat. Proin porttitor ullamcorper ligula. Sed sit amet dictum erat. Curabitur eget sem diam. Quisque hendrerit, sem vitae egestas mollis, sem ipsum porttitor nibh, a faucibus urna urna eu nulla. Integer orci felis, vestibulum eget nibh eu, pellentesque scelerisque velit. Maecenas vel mollis tellus. Integer commodo mauris scelerisque consectetur tempus. Nulla eu turpis ornare, scelerisque eros et, convallis urna. Quisque ac sapien sed lacus posuere fringilla vel eu ante. Suspendisse felis enim, viverra eu diam eu, posuere convallis ante. Etiam vel arcu turpis.', 'keys': ['spectrum', 'video game', 'portable'] }

It's like the package.json of the npm/grunt. And for read the file, I use:

/**
 * JSON
 */
var json = fs.readFileSync(__dirname + '/apps/SpectrumApp/package.json');

log.debug('json = ' + json);
log.debug('json.name = ' + json['name']);

Finally the first output it's the same as above and the second is "undefined" even if I do json.name. Other things I've tried was JSON.stringify and then JSON.parse, and just JSON.parse... but nothing works and when I try to access any of the attributes, the output is the same "undefined".

What I did wrong?

Thank you so much!

EDIT: When I try to do JSON.parse in the var json, the output is:

undefined:2
    'name': 'SpectrumApp',
    ^
SyntaxError: Unexpected token '
    at Object.parse (native)
    at Object.<anonymous> (/home/todi/Projetos/Spectrum/src/server/server.js:178:28)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3
1
That's a string, not an object. - SLaks
Your file is not json. See: json.org . The names/keys need double quotes. You can check your json here: jslint.com - bluelDe

1 Answers

5
votes

Use JSON.parse after having transformed your single quotes to double quotes for getting valid JSON:

var jsonString = fs.readFileSync(__dirname + '/apps/SpectrumApp/package.json').replace(/\'/g, "\"")
var json = JSON.parse(jsonString);

Alternatively, you can require the file and import it as JSON directly, if your file already contains valid JSON. This method is primarily intended for configuration usage:

var json = require(__dirname + '/apps/SpectrumApp/package.json');