I want to read data from a file and add it to an Object stored in memory. The data in the file text.txt looks roughly like this:
One: {title: 'One' ,
contributor: 'Fred',
summary: 'blah' ,
comments: 'words' },
Two: {title: 'Two' ,
contributor: 'Chris' ,
summary: 'blah blah i'm a blah' ,
comments: '' },
I'm trying to set it to an empty Object like so:
var fs = require('fs');
var text = Object.create(null);
fs.readFile("./public/text.txt", "utf-8", function(error, data) {
text = { data };
});
However, when I log text to the console, it comes out looking like this:
{ data: 'One: {title: \'One\' ,\ncontributor: \'Fred\',\nsummary: \'blah\' ,\ncomments: \'words\' },\n \nTwo: {title: \'Two\' ,\ncontributor: \'Chris\' ,\nsummary: \'blah blah i\'m a blah\' ,\ncomments: \'\' },\n\n' }
Apparently, it's reading data as a key. What I really want, though, is something more like so:
{
One: {title: 'One' ,
contributor: 'Fred',
summary: 'blah' ,
comments: 'words' },
Two: {title: 'Two' ,
contributor: 'Chris' ,
summary: 'blah blah i'm a blah' ,
comments: '' },
}
Any advice here would be much appreciated.
JSON.parse(data);. See duplicate: Using Node.JS, how do I read a JSON object into (server) memory?Syntax Error: Unexpected token O{}curly brackets. That creates some difficulties for me; is there any way to avoid that?Syntax Error: Unexpected token O. A: Then your Json file is illegal. SUGGESTION: make sure you've got{...}delimiting your outermost "data" node. The answer to the question you posted is "use JSON.parse()". The answer to your syntax error is "fix your JSON file".