JavaScript: read and write json file

Viewed 50

I have generated json file from my consumer pact in javaScript. When it's generating json file it doesn't contain what I expect. So, now I want to add block to my json file which I don't know how to do? Can someone here help me with that? so, basically I want to read json then create block and then write into json and save data

"path": {
  "dataType": "String",
  "expression": "data/xml/${id}",
  "key": "request"
}

Thanks,

1 Answers

As @Barmar pointed out you can simply parse your JSON text and modify it.

let yourJsonText = "{...}"; // read in your json however you want
let yourJson = JSON.parse(yourJsonText);

// then modify your object
yourJson.path.newAttr = "something you like";

// parse it back to a JSON string
let yourUpdatedJsonText = JSON.stringify(yourJson);
Related