Open/Save local (JSON) file from JavaScript >> IE/Firefox Open/Save local (JSON) file from JavaScript >> IE/Firefox json json

Open/Save local (JSON) file from JavaScript >> IE/Firefox


To load the file, it must already exist on the server. It can then be loaded as part of your script (either lazy loaded, or include in the head) - or loaded with the .load() method of the jQuery AJAX library. If it isn't on the server, you'll need to do an upload first [this is to prevent XSS].

You can use the .load(), .get() or the full .ajax() jQuery calls to pull the data from that point. Look here: http://api.jquery.com/load/

For the saving of data - use a cookie to store the data that way, post the data into a new window (form submission) or if you still want it in the querystring your method should work.

Note I use a different JSON library but the below executes in both IE and FF.

  $(document).ready(function() {    var obj = { name: 'John', max: 100 };    window.open("data:text/json;charset=utf-8," + escape($.toJSON(obj)))   })

I'd reccomend that to pass it you do something like:

  function saveJSON(){    var obj = {};    obj.name = 'John';    obj.max = 100;    $("#json").val($.toJSON(obj));    $("#hiddenForm").submit();  }

And a simple form to contain it...

<form action="somepageToDisplayFormFields.php" target="_blank" id="hiddenForm">  <input type="hidden" name="json" id="json" /></form>

This will allow you to pass more (and more complex) objects across without running into URI size limitations, and cross browser functional differences. Plus trying to work out escape(), escapeURIComponent(), etc... will drive you nuts eventually.


Well, I found a solution to reading a client-side file which works pretty good. It's also not completely insecure since "direct and intentional user intervention is required to expose individual files to the script". Currently it works for me on Firefox only, so I guess I'll have to settle with this constraint for now.

Thank you all for your comments and answers; they've been very helpful and I've learned a lot.


Direct file system manipulation is something that is generally not allowed from client side javascript (with good reason. do you want random websites poking around in your files?))

nevertheless, you can more or less accomplish your first goal just by making your JSON a download link- Put your DATA url into the href of a link and that should work in IE's starting with IE8. with older IE's you're SOL.

As for getting a JSON file from a path, there is a PROPRIETARY, FIREFOX ONLY property that allows you to do this. documented here: https://developer.mozilla.org/en/DOM/File