Monday, July 25, 2022

[FIXED] How to check if uploaded file is a JSON file?

Issue

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.


Solution

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');  
    }


Answered By - CodingWolf
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.