42

I have a html code like this:

<input type="file" id="up" />
<input type="submit" id="btn" />

And I have a JSON file like this:

{
 "name": "John",
 "family": "Smith"
}

And a simple JavaScript function:

alert_data(name, family)
{
     alert('Name : ' + name + ', Family : '+ family)
}

Now I want to call alert_data() with name and family that stored in JSON file which uploaded using my HTML input.

Is there any way to use an HTML5 file reader or something else?
I'm not using server-side programming, all of them are client-side.

leonheess
  • 10,362
  • 9
  • 56
  • 89
Masoud Aghaei
  • 978
  • 1
  • 16
  • 25

4 Answers4

63

You will need an HTML5 browser, but this is possible.

(function(){
    
    function onChange(event) {
        var reader = new FileReader();
        reader.onload = onReaderLoad;
        reader.readAsText(event.target.files[0]);
    }

    function onReaderLoad(event){
        console.log(event.target.result);
        var obj = JSON.parse(event.target.result);
        alert_data(obj.name, obj.family);
    }
    
    function alert_data(name, family){
        alert('Name : ' + name + ', Family : ' + family);
    }
 
    document.getElementById('file').addEventListener('change', onChange);

}());
<input id="file" type="file" />

<p>Select a file with the following format.</p>
<pre>
{
  "name": "testName",
  "family": "testFamily"
}    
</pre>
Sam Greenhalgh
  • 5,764
  • 19
  • 36
  • 5
    working perfectly as of Nov 2019. I was asked to extract data from a json file onUpload – Akhil Nov 08 '19 at 13:15
13

Here's a shorthand version of Sam Greenhalghs answer that works for me.

$(document).on('change', '.file-upload-button', function(event) {
  var reader = new FileReader();

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

  reader.readAsText(event.target.files[0]);
});
<input class='file-upload-button' type="file" />
Sam Whillance
  • 151
  • 1
  • 3
11

Since all answers seem unnecessarily complex here's a simple function that returns the file contents as an Object:

async function fileToJSON(file) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()
    fileReader.onload = event => resolve(JSON.parse(event.target.result))
    fileReader.onerror = error => reject(error)
    fileReader.readAsText(file)
  })
}
leonheess
  • 10,362
  • 9
  • 56
  • 89
  • 1
    This is an amazing solution. Just use it in an async function and it will give you what you need. Thanks @leonheess – Aiden Pearce Mar 22 '22 at 23:04
2

Yep! It can be done with HTML5 FileReader. And it's actually pretty simple.
Save the json as a .js file and load it in my example

{
 "name": "John",
 "family": "Smith"
}

This is where the magic happens:

$("#up").change(function(event){
    var uploadedFile = event.target.files[0]; 
    
     if(uploadedFile.type !== "text/javascript" && uploadedFile.type !== "application/x-javascript") { 
        alert("Wrong file type == " + uploadedFile.type); 
        return false;
    }
    
    if (uploadedFile) {
        var readFile = new FileReader();
        readFile.onload = function(e) { 
            var contents = e.target.result;
            var json = JSON.parse(contents);
            alert_data(json);
        };
        readFile.readAsText(uploadedFile);
    } else { 
        console.log("Failed to load file");
    }
});

function alert_data(json)
{
     alert('Name : ' + json.name + ', Family : '+ json.family)
}

Fiddle link with this code: http://jsfiddle.net/thomas_kingo/dfej7p3r/3/
(The uploadedFile.type check is only tested in Chrome and firefox)

Guy Coder
  • 23,219
  • 7
  • 62
  • 122
  • Please [avoid link only answers](http://meta.stackoverflow.com/tags/link-only-answers/info). Answers that are "barely more than a link to an external site” [may be deleted](http://stackoverflow.com/help/deleted-answers). – Quentin Nov 23 '14 at 15:03