Download JSON Object as a File from Browser

Download JSON object as a file from browser

This is how I solved it for my application:

HTML:
<a id="downloadAnchorElem" style="display:none"></a>

JS (pure JS, not jQuery here):

var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(storageObj));
var dlAnchorElem = document.getElementById('downloadAnchorElem');
dlAnchorElem.setAttribute("href", dataStr );
dlAnchorElem.setAttribute("download", "scene.json");
dlAnchorElem.click();

In this case, storageObj is the js object you want to store, and "scene.json" is just an example name for the resulting file.

This approach has the following advantages over other proposed ones:

  • No HTML element needs to be clicked
  • Result will be named as you want it
  • no jQuery needed

I needed this behavior without explicit clicking since I want to trigger the download automatically at some point from js.

JS solution (no HTML required):

  function downloadObjectAsJson(exportObj, exportName){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}

How to download a json object as file?

var jsonVariable = JSON.stringify(req.user);
var path_tmp = create_tmp_file(jsonVariable);
res.download(path_tmp);

Send the data with res.json and use content-disposition to make it a download.

res.set('Content-Disposition', 'attachment; filename=example.json')
res.json(req.user);


res.redirect('/about');
next();

And don't do that (which is the cause of the error). You are responding with a download. You can't say "Here is the file you asked for" while, at the same time say, "The file you asked for isn't here, go to this URL instead".

how to download json object as file from browser

You can make use of the download attribute of the anchor tag(I don't know how well supported it is) and the html5 file api.

<a href = "#" id = "save" download="data.json">Save Canvas 1</a>
Load Canvas<input type="file" id="load" />
$( "#save" ).click(function( event ) {
this.href = 'data:plain/text,' + JSON.stringify(canvas1)
});
$( "#load" ).change(function( event ) {
var fr = new FileReader();
fr.onload = function(){
canvas2.loadFromJSON(this.result, canvas2.renderAll.bind(canvas2));
}
fr.readAsText(this.files[0]);
});

http://jsfiddle.net/P9cEf/5/


Here is a version or new IE (IE11 at least)

$( "#save" ).click(function( event ) {
event.preventDefault();
var blob = new Blob([JSON.stringify(canvas1)],{type:'application/json'});
navigator.msSaveOrOpenBlob(blob, 'data.json');
});

http://jsfiddle.net/P9cEf/7/

React:write to json file or export/download [no server]

I had a blob containing data and I had found a solution on stackoverflow and manipulated a bit, and succeded to download as a xlsx file. I am adding my code below, it might help you, too.

const blob =  await res.blob(); // blob just as yours
const href = await URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.download = "file.xlsx";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

EDIT: You can use the function below, but be sure to switch out fileName and myData from this.state to something that will work in your application.

const downloadFile = () => {
const { myData } = this.state; // I am assuming that "this.state.myData"
// is an object and I wrote it to file as
// json

// create file in browser
const fileName = "my-file";
const json = JSON.stringify(myData, null, 2);
const blob = new Blob([json], { type: "application/json" });
const href = URL.createObjectURL(blob);

// create "a" HTLM element with href to file
const link = document.createElement("a");
link.href = href;
link.download = fileName + ".json";
document.body.appendChild(link);
link.click();

// clean up "a" element & remove ObjectURL
document.body.removeChild(link);
URL.revokeObjectURL(href);
}

More documentation for URL.createObjectURL is available on MDN. It's critical to release the object with URL.revokeObjectURL to prevent a memory leak. In the function above, since we've already downloaded the file, we can immediately revoke the object.

Each time you call createObjectURL(), a new object URL is created, even if you've already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them.

Browsers will release object URLs automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so.

Download Object As Formatted JSON File

The JSON.stringify has three parameters, you can use third parameter for that

JSON.stringify(json, null, 4);

How do I save JSON to local text file

Node.js:

var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
if (err) {
console.log(err);
}
});

Browser (webapi):

function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');

Converting Object into JSON and downloading as a .json file in React

I'm not sure this is a React-specific issue if you're just looking to download data via JavaScript, but here's a snippet I use that creates a link to download the data content, virtually clicking the element, and finally removing it from the DOM. It should support both modern browsers and older IEs:

private exportToJson(objectData: SomeObject) {
let filename = "export.json";
let contentType = "application/json;charset=utf-8;";
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([decodeURIComponent(encodeURI(JSON.stringify(objectData)))], { type: contentType });
navigator.msSaveOrOpenBlob(blob, filename);
} else {
var a = document.createElement('a');
a.download = filename;
a.href = 'data:' + contentType + ',' + encodeURIComponent(JSON.stringify(objectData));
a.target = '_blank';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}

It's also worth noting that there are a number of ways to approach this as cited in this SO question.

How to produce a file to download containing a JSON structure?

Convert the data into bytes then those bytes into a FileResult. You return the FileResult and the browser will do whatever it does normally when presented with a 'file', usually either prompt the user or download.

Example below:

public ActionResult TESTSAVE()
{
var data = "YourDataHere";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
var output = new FileContentResult(bytes, "application/octet-stream");
output.FileDownloadName = "download.txt";

return output;
}

In your case you would simply take your JSON data as a string.



Related Topics



Leave a reply



Submit