0

I'm new to Node.js. I have a JSON object which looks like the following:

var results = [
  { key: 'Name 1', value: '1' },
  { key: 'Name 2', value: '25%' },
  { key: 'Name 3', value: 'some string' },
  ...
];

The above object may or may not have different values. Still, I need to get them into a format that looks exactly like the following:

{"Name 1":"1","Name 2":"25%","Name 3":"some string"}

In other words, I'm looping through each key/value pair in results and adding it to a single line. From my understanding this single line approach (with double quotes) is called "JSON Event" syntax. Regardless, I have to print my JSON object out in that way into a text file. If the text file exists, I need to append to it.

I do not know how to append to a text file in Node.js. How do I append to a text file in Node.js?

Thank you!

user3469584
  • 613
  • 3
  • 10
  • 15

1 Answers1

0

You can use JSON.stringify to convert a JavaScript object to JSON and fs.appendFile to append the JSON string to a file.

// write all the data to the file
var fs = require('fs');
var str = JSON.stringify(results);
fs.appendFile('file.json', str, function(err) {
    if(err) {
        console.log('there was an error: ', err);
        return;
    }
    console.log('data was appended to file');
});

If you want to add just one item at a time, just do

// Just pick the first element
var fs = require('fs');
var str = JSON.stringify(results[0]);
Hector Correa
  • 26,290
  • 8
  • 57
  • 73