1

I need to load json from local filesystem. This is what I tried:

index.htlm:

<html>
    <head>
        <title>JSON File Locally by Javascript Without JQuery</title>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body onload="loadJSON()">
        Load JSON File Locally by Javascript Without JQuery
    </body>
</html>

script.js:

function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'employee.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
}
xobj.send(null);

}
loadJSON(function(response) {
jsonresponse = JSON.parse(response);

console.log(jsonresponse[0].name);

});

employee.json:

[{"name" : "Harry", "age" : "32"}]

But nothing cant be read on console.log output. I tried with XMLHttpRequest() function but soon realised it is only for web based json files. Any help is appreceated.

user2727167
  • 428
  • 1
  • 3
  • 16
  • 1
    Please consider this question https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file#:~:text=Yes%20js%20can%20read%20local,the%20file%20or%20files%20content. – vvs Feb 07 '21 at 22:15

2 Answers2

1

What you're asking for simply isn't possible- browsers do not give javascript access to the filesystem for security reasons. You'll need to serve the file over HTTPS (through a backend server) or take a different approach to your overall problem.

Robert Hafner
  • 3,364
  • 18
  • 23
-1

I assume with 'local file system' you mean a local installed server like xampp!? In that case, - maybe you like to keep it simple:


<script>
    
    window.onload = function(){

        function loadJson(){
            
            const xobj = new XMLHttpRequest();
            xobj.open('POST', 'employee.json');

            xobj.onreadystatechange = function () {

                if (xobj.readyState == 4 && xobj.status == "200") {
                    
                    let data = xobj.responseText;
                    data = JSON.parse(data);

                    console.log(data[0]['name']);
                }

            }//xobj.onreadystatechange

            xobj.send(null);

        }
        
        loadJson();

    }


</script>


Brebber
  • 2,986
  • 2
  • 9
  • 19