0

I want to read a local Json file from a html page. But I am not able to read the local Json file in HTML page that work for chrome and IE. Is there is any way to do it without using any web server.

3 Answers3

0

Let's say you have, index.html & sample.json in the same folder, you can do this,

$http.get('sample.json').then(function(response) {
    console.log(response);
 });

of course you will need to run this from a controller, stand alone or in a directive, etc.

z.a.
  • 2,549
  • 3
  • 12
  • 16
0

I found this solution on the web, i didn't try it but according to the comments it should work

function loadJSON(callback) {   

    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
          }
    };
    xobj.send(null);  
 }

The function above will create a new instance of a XMLHttpRequest and load asynchronously the contents of my_data.json. I have gone with asynchronous but you can change the argument to false if you want a synchronous load. Thankfully all modern browsers support the native JSON.parse method. Remember our anonymous callback? here's how you use it.

function init() {
 loadJSON(function(response) {
  // Parse JSON string into object
    var actual_JSON = JSON.parse(response);
 });
}``

http://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript

NDZIE Patrick Joel
  • 1,114
  • 14
  • 26
-1

Create a JSON file named sample.json in a translation folder .Then in controllers use the below code to get the values present in JSON file

$http.get('translation/sample.json').success(function(response){
      console.log(response);           
});

or

$.getJSON('translation/sample.json', function(data){
    console.log(data); 
});
  • You can edit your question please, explanations are for the community, not for me ;) – GGO Feb 22 '18 at 08:56