1
votes

I want to create a data file called data.json(if it is not already created), then I want to insert 2 keys and 1 value.

Example: file is empty, add key1, keyA, value1, keyB, value2 data.json would look like

{key1: {keyA: value1, keyB: value2}}

Example2: file is currently

{key1: {keyA: value1, keyB: value2}}

add second key2, keyC, keyD value3, value4 to data.json would look like

{
key1: {keyA: value1, keyB: value2},
key2: {keyC: value3, keyD: value4}
}
1

1 Answers

0
votes

To create/write a JSON file, you can do the following program

const {writeFileSync} = require("fs");
writeFileSync("data.json",JSON.stringify({/* JSON HERE */})

To edit JSON, you can do

const fs = require("fs");
var jsonData = fs.readFileSync("data.json");
var json = JSON.parse(jsonData);

The variable json contains the JSON data from the file. Use the first script to then write the new JSON data.