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.”

Leave a Comment