Node.js – create dynamic json object and write to .json file

I am new to JS ecosystem and a requirement is to create a json object dynamically at run time and to write it to .

{
  "prerequisite": [
    {
      "url1": "",
      "step1": {},
      "step2": {}
    }
  ],
  "PF": [
    {},
    {}
  ]
}

I tried using new Object() but not sure how to build this complex one (to my extent its complex ).

For writing it to file i understand using FS we can achieve it.

Need support on building this json object at run time

Answer

I guess you’d like to do something like this. I’m not sure how you want to make it dynamic, but if you have a json object, you can always add to it like this: json_obj.something = “anything”

And it save (overwrite) every time when it runs. Save this code to a file (like filename.js) and run it. (node filename.js)

Oh and must be stringify the json since the FS “data” argument must be of type string or an instance of Buffer, TypedArray, or DataView

const fs = require("fs")
const FILE = "./json_obj.json"

const json_obj = {
  prerequisite: [
    {
      url1: "",
      step1: {},
      step2: {},
    },
  ],
  PF: [{}, {}],
}

fs.writeFile(FILE, JSON.stringify(json_obj), (err) => {
  if (err) {
    console.error(err)
    return
  }
})