Home > other >  Append an array of objects to an empty JSON file
Append an array of objects to an empty JSON file

Time:03-10

I have an array of objects:

[
  { one: 1, two: 2, random: 49 },
  { one: 1, two: 2, random: 1 },
  { one: 1, two: 2, random: 3 },
  { one: 1, two: 2, random: 29 },
  { one: 1, two: 2, random: 30 },
  { one: 1, two: 2, random: 35 },
  { one: 1, two: 2, random: 42 },
  { one: 1, two: 2, random: 26 }
]

I have a single empty object in a json file like this:

{}

I need the result to look like this:

{
  { 
     "one": 1, 
     "two": 2, 
     "random": 49 
  },
  { 
    "one": 1, 
    "two": 2, 
    "random": 1 
  },
  { 
    "one": 1, 
    "two": 2, 
    "random": 3 
  },
  ...
}

how can this be done in node.js?

CodePudding user response:

You can use JSON.stringify and the instructions here: https://nodejs.org/en/knowledge/file-system/how-to-write-files-in-nodejs/

const myObj = [
  { one: 1, two: 2, random: 49 },
  { one: 1, two: 2, random: 1 },
  { one: 1, two: 2, random: 3 },
  { one: 1, two: 2, random: 29 },
  { one: 1, two: 2, random: 30 },
  { one: 1, two: 2, random: 35 },
  { one: 1, two: 2, random: 42 },
  { one: 1, two: 2, random: 26 }
]
fs = require('fs');
fs.writeFile('myfile.json', JSON.stringify(myobj), function (err) {
  if (err) return console.log(err);
  console.log('Writing myObj > myfile.json');
});

As Nick wrote, this will not output the format you specified, because that is invalid. It will output an array.

CodePudding user response:

The Object needs to be key-value pair. You can't assign property in Object without the key. Here is a nice article from where you can learn about the Javascript Object. The format you wanted is not valid, so try to fulfil your requirement with array like data-structure where you can push the data based on sequential index.

  • Related