Save JSON String to Client Pc (Using HTML5 API)

Save json string to client pc (using HTML5 API)

You can use a Blob and the HTML5 a[download] feature to provide a JSON backup download:

var data = {a:1, b:2, c:3};
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "application/json"});
var url = URL.createObjectURL(blob);

var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
a.textContent = "Download backup.json";

Here is a jsfiddle example: http://jsfiddle.net/potatosalad/yuM2N/

Writing a json object to a text file in javascript

One thing you can do is setup the JSON as a download on the fly.

var data = "{name: 'Bob', occupation: 'Plumber'}";
var url = 'data:text/json;charset=utf8,' + encodeURIComponent(data);
window.open(url, '_blank');
window.focus();

Working demo: http://jsfiddle.net/sLq3F/

Apart from that, you can't write a JSON to a file on the clientside due to security reasons. (Otherwise you have access to the filesystems of your website's users.) You would have to use a server-side language for this, and store the file on the server-side.


Correction: Looks like you can write to a file, i.e., a "sandboxed section" of the user's filesystem. See Kevin Jantzer's comment below.

Another Correction: Sorry, the Filesystem API isn't in use. From the HTMl5Rocks website: "In April 2014, it was announced on public-webapps that the Filesystem API spec should be considered dead. Other browsers have showed little interest in implementing it."

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();
}

Using HTML5/JavaScript to generate and save a file

OK, creating a data:URI definitely does the trick for me, thanks to Matthew and Dennkster pointing that option out! Here is basically how I do it:

1) get all the content into a string called "content" (e.g. by creating it there initially or by reading innerHTML of the tag of an already built page).

2) Build the data URI:

uriContent = "data:application/octet-stream," + encodeURIComponent(content);

There will be length limitations depending on browser type etc., but e.g. Firefox 3.6.12 works until at least 256k. Encoding in Base64 instead using encodeURIComponent might make things more efficient, but for me that was ok.

3) open a new window and "redirect" it to this URI prompts for a download location of my JavaScript generated page:

newWindow = window.open(uriContent, 'neuesDokument');

That's it.

How do I create a download from a json structure in a scope variable

Downloading the JSON data, means downloading a file containing a JSON string.
If you are already able to render that file on the server, then you just need to create an html link, with the href attribute pointing to the corresponding server url.

In order to force the file to be downloaded, you have to declared it as an attachment in an http header.
The response must contains something like this:

'Content-Disposition: attachment; filename=data.json'

You can also specify the content-type with another response header:

'Content-Type': application/json

Edit: I just discovered that apparently you can initialize a file download directly from the client. See this SO topic. Seems to be pretty well supported: http://caniuse.com/#feat=bloburls

How to download a json file which is coming from odata service in sapui5?

I've solved this issue.

onDataDownload: function () {
//call the function
let obj = model.getInstance().getModelService().bindContext("/abcd(...)", undefined, {
$$updateGroupId: "anyName"
});

obj.execute("anyName").then(function () {
var encoded = obj.getBoundContext().getObject().value;
var decoded = atob(encoded);
const blob = new Blob([decoded], { type: "application/json" });

if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, "ABCD.json");

} else {
const ele = window.document.createElement("a");
ele.href = window.URL.createObjectURL(blob);
ele.download = "ABCD.json";
document.body.appendChild(ele);
ele.click();
document.body.removeChild(ele);

}

});
model.getInstance().getModelService().submitBatch("anyName");
}

How to save new state to local json

You can't access the file system from the browser for security reasons. If you just want to access it after refreshing, I guess that you could save it in localStorage when you modify the state and then use it when the component is loaded it if it's not undefined (you can check this in componentDidMount). (The code below is not tested)

addEmployee(employee) {
let newEmployees = this.state.employees.concat([employee])
localStorage.setItem('employees', JSON.stringify(newEmployees));
this.setState({
employees: newEmployees
});
}

componentDidMount(){
let newEmployees = localStorage.employees
if(newEmployees != undefined){
this.setState({
employees: JSON.parse(newEmployees)
});
}
}

If you want to store that JSON persistently and you want more than being able to use it after refreshing, you should do it on the backend. You can also let the user save the file manually (with a download prompt) as it's described here.

How to read an external local JSON file in JavaScript?

You cannot make a AJAX call to a local resource as the request is made using HTTP.

A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.

In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON():

http://api.jquery.com/jQuery.getJSON/



Related Topics



Leave a reply



Submit