Home > Software design >  How to check if uploaded file is a JSON file?
How to check if uploaded file is a JSON file?

Time:07-09

I am taking a file input from a user and I want to check if the selected file is a JSON file. How can I do that?

<input type = "file" onChange = {checkJSON}/>

Also how do I retrieve data from the JSON file.

CodePudding user response:

If JSON.parse throws an error, its most likely invalid, therefore you can check if its valid by getting the data into a string and then trying to parse it.

    try {  
      const json = JSON.parse(jsonStr);  
    } catch (e) {  
      console.log('invalid json');  
    }

CodePudding user response:

You can check if file extension is json and be sure that selected file is valid JSON in that way:

function Validate() {
  fileName = document.querySelector('#myfile').value;
  extension = fileName.split('.').pop();
  if (extension != "json")
  {
   alert("Sorry, "   fileName   " is invalid, allowed extension is json!");
   return false;
  }
  
  var file = document.getElementById('myfile').files[0];
  var reader = new FileReader();
  reader.readAsText(file, 'UTF-8');
  reader.onload = function(evt) {
    var jsondata = evt.target.result;
    try {  
      const json = JSON.parse(jsondata);  
      document.getElementById('jsondata').innerHTML = jsondata;
    } catch (e) {  
      alert("Sorry, "   fileName   " is not valid JSON file!");
      return false;  
    }
  }
  return true;
};

Html content:

<script src="script2.js"></script>
File: <input type="file" id="myfile" onchange="Validate()"/><br /><br />
<div id="jsondata"></div>

You can play with my little working live demo on ReplIt (both cases - onsubmit and onchange demos)

  • Related