-2

I want to generate a .json file on my local project folder. I want to save the fetch API call response (which is an array of objects) into a .json file Here is my code : ts :

 getRecords(){

   this.service.getRecords()
    .subscibe((res)=>{
      // res.data -want to convert this data into .json file
      });

 }
P J
  • 70
  • 1
  • 4
  • 25

1 Answers1

0

I'm not sure if you want to be able to do this locally (i.e., so the user can download a JSON file), or if you want to do this using Node.js, so here's both approaches.

I mention Nodejs since you tagged this with Angular.

If you are using NodeJS, you can use the fs module:

let json = {"foo": "bar"};
let str = JSON.stringify(json);

let fs = require("fs");
fs.writeFile("jsonFile.json", str, function(error) {
    if (error) {
        console.log("Error");
    } else {
        console.log("Success");
    }
);

But if you want to create a file from the browser and download on the client machine:

let json = {"foo": "bar"};
let str = JSON.stringify(json);

let str = "data:text/json;charset=utf-8," + encodeURIComponent(str);
let dl = document.createElement("a");
dl.setAttribute("href", str);
dl.setAttribute("download", "jsonFile.json");
dl.click();

Also, your code did not get added to your question.

JoshG
  • 6,472
  • 2
  • 38
  • 61