49

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
  • 16,068
  • 14
  • 77
  • 112
Masoud Aghaei
  • 1,113
  • 2
  • 15
  • 27

4 Answers4

69

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,952
  • 21
  • 37
19

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

async function parseJsonFile(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)
  })
}

const object = await parseJsonFile(file)
leonheess
  • 16,068
  • 14
  • 77
  • 112
  • 2
    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
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
  • 149
  • 1
  • 4
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
  • 24,501
  • 8
  • 71
  • 136
  • 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