Save API request response as JSON file

Asked

Viewed 441 times

-1

When making a request to the URL(API), the result is a JSON. How can I save this JSON to a.json file locally on my machine? My code so far:

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://urldaapi");
xhr.send();
console.log(xhr);

1 answer

0


You can use this function by only changing its url:

(function (fetch, console) {
    fetch('https://urldaapi')
    .then(res => res.json())
    .then(data => console.save(data));

    console.save = function (data, filename) {

        if (!data) {
            console.error('Console.save: No data')
            return;
        }

        if (!filename) filename = 'console.json'

        if (typeof data === "object") {
            data = JSON.stringify(data, undefined, 4);
        }

        var blob = new Blob([data], {type: 'text/json'}),
            e    = document.createEvent('MouseEvents'),
            a    = document.createElement('a');

        a.download = filename;
        a.href = window.URL.createObjectURL(blob);
        a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':');
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        a.dispatchEvent(e);
    };

}).call(this, window.fetch, window.console || {});

I hope I’ve helped.

  • After you have saved the file how do I access a value of this file change it and save it again? I need to manipulate the values of this file

Browser other questions tagged

You are not signed in. Login or sign up in order to post.