javascripthtmljsonfile-io

Read JSON from from HTML file input


If I have an input:

<input type="file" id="upload" onchange="getFile(this)">

And my user will upload a JSON file (as plaintext, so I will have to use JSON.parse()), how can I take this file and actually get the data via getFile()

In getFile(element), I've tried using element.files[0] but that doesn't seem to contain the actual data. I've also looked here, here, and here, but none of these solve my problem. This resource on MDN seems promising, but I don't really get it.

I would like a solution involving either URL.createObjectURL() or FileReader().

Also, before anyone posts this in the comments, I do understand that these solutions do not work on all browsers, and I would like to do this from the frontend.


Solution

  • You could take advantage of the Response constructor and call .json() on any blob/file.

    function getFile (elm) {
      new Response(elm.files[0]).json().then(json => {
        console.log(json)
      }, err => {
        // not json
      })
    }
    

    Alternative method using the new read methods on blob.prototype[...]

    new Blob(['1']).text().then(JSON.parse).then(console.log)
    // handles emptying file input with ?.
    elm.files[0]?.text().then(JSON.parse).then(console.log)
    

    I guess for larger files response.json might be faster/better since it can parse the content in background and not block the main UI unlike JSON.parse