How to execute data from json file via File API?

1.7k views Asked by At

I am novice in File API. At the moment I have a task to execute data from json-file using File API and drag-and-drop method. JSON-file example:

[
    {
        "id":2,
        "name":"VoffCafe",
        "coordinates":{
            "latitude":56.629418,
            "longitude":47.893927
        }
    }
]

Data from JSON-file must be written to some variables.

Now I have an example, it is sample on my task, but it shows picture, which is dropped on web-page. Script from this example, which does this, below:

<script>
  var holder = document.getElementById('holder'),
  state = document.getElementById('status');

  if (typeof window.FileReader === 'undefined') {
  state.className = 'fail';
  } else {
  state.className = 'success';
  state.innerHTML = 'File API & FileReader available';
  }

  holder.ondragover = function () { this.className = 'hover'; return false; };
  holder.ondragend = function () { this.className = ''; return false; };
  holder.ondrop = function (e) {
  this.className = '';
  e.preventDefault();

  var file = e.dataTransfer.files[0],
  reader = new FileReader();
  reader.onload = function (event) {
  console.log(event.target);
  holder.style.background = 'url(' + event.target.result + ') no-repeat center';
  };
  console.log(file);
  reader.readAsDataURL(file);

  return false;
  };
</script>

Full page-example, where this script works is here: http://html5demos.com/file-api

How to redo this script to it be satisfied my demands?

1

There are 1 answers

0
Burdock On BEST ANSWER

You can brake down the task of a "local JSON file grabber" into 3 main steps:

1: The file selector

The ondrop event operates as our file selector in this example. see documentation here.

var holder = document.getElementById('holder');

   holder.ondrop = function (e) { 
   var file = e.dataTransfer.files[0]; //Gets the most recent dropped file 
   ...do FileReader stuff...
   return false; 
   }  

2: The Filereader

Javascript's Filereader often confuses people due to its asynchronous nature. Long story short : In the code below the reader.onload function is called after reader.readAsText() is completed. see documentation here

var reader = new FileReader();
//.onload event is triggered each time the reading operation is successfully completed.
reader.onload = function (event) {
 ...do Parser stuff... 
}
reader.readAsText(file);//Passes reader the file to read as text (aka String) 

3. The Parser

Once you have a string to parse, turning it into an object is dead simple with JSON.parse(). In this example just pass in the file contents with event.target.result.

reader.onload = function (event) {
    var parsedObj = JSON.parse(event.target.result); 
}

putting it all together

//JSON file (removed unnecessary brakets)  
{
    "id":2,
    "name":"VoffCafe",
    "coordinates":{
        "latitude":56.629418,
        "longitude":47.893927
    }
}

//HTML file
<script>
var holder = document.getElementById('holder'); 

/*
...Other stuff...
*/

//Step 1 : The File Selector
holder.ondrop = function (e) {
    this.className = '';
    e.preventDefault(); // Keeps any default action the element from happening

    var file = e.dataTransfer.files[0];
    console.log(file);


    //Step 2 : The File Reader    
    var reader = new FileReader();
    reader.onload = function (event) {

        //Step : 3 The Parser 
        var parsedObj = JSON.parse(event.target.result);

        //example code : alerts all the methods of parsedObj.
        for(I in parsedObj) {
            if(parsedObj.hasOwnProperty(I)){
                alert(parsedObj[I]);
            }
        }
    };

    reader.readAsText(file);
    return false;
};
</script>

I hope that helps!