Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HTML 5 File API to load a JSON file

I want the user to be be able to chose a JSON file on there computer, this JSON file should then be made available to the client side Javascript.

How would I do this using the FILE API, the ultimate goal is the the user selected JSON file to be available as an object which I can then play about with in Javascript. This is what I have so far:

JsonObj = null 



function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
     f = files[0];
      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
         JsonObj = e.target.result
         console.log(JsonObj);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }



document.getElementById('files').addEventListener('change', handleFileSelect, false);

FIDDLE: http://jsfiddle.net/jamiefearon/8kUYj/

How would I convert the variable JsonObj to a proper Json object, one can can add new fields to etc.

like image 905
Jamie Fearon Avatar asked Feb 06 '13 23:02

Jamie Fearon


People also ask

How fetch data from JSON to HTML?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.


1 Answers

Don't load the data as a "DataUrl" via readAsDataURL, instead use readAsText then parse it via JSON.parse()

e.g.

JsonObj = null 

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
     f = files[0];
      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
         JsonObj = JSON.parse(e.target.result);
         console.log(JsonObj);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsText(f);
    }

document.getElementById('files').addEventListener('change', handleFileSelect, false);
like image 94
Grant Peters Avatar answered Sep 28 '22 01:09

Grant Peters