-1

I've been trying for some time to read a local JSON file with pure Javascript (no JQuery). I searched the whole Google and Stackoverflow, but it seems that nothing works in my case. I know the JSON.parse, but how do I read the file in the first place on my Javascript?

loadJSON(json){
    var savedJSON = JSON.parse(json);
    alert(savedJSON[0].name);
}

The main idea is to have a server website to generate a JSON that has the user's saved information, and now I will read the JSON and generate a HTML with that information to use in a Android app, but I'm struggling at reading the JSON. Any idea?

SidneyReis
  • 11
  • 1

1 Answers1

0

As suggested in http://www.w3schools.com/json/json_http.asp you can read the local (on the server) text file with an XMLHttpRequest

This code will print a JSON array in an HTML table. Contents of file file.json:

[[ 50.65, 5.37 , 4358684.11 ], 
 [ 50.68, 5.86 , 1849705.79 ], 
 [ 50.33, 6.84 ,  961107.46 ], 
 [ 50.55, 7.32 , 1587473.93 ]]

HTML/Javascript

<script>
var xmlhttp = new XMLHttpRequest();
var url = "file.json";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myArr = JSON.parse(xmlhttp.responseText);
        myFunction(myArr);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
    var out = "<table border=1>";
    var i;
    for(i = 0; i < arr.length; i++) {
        out += "<tr>";
        for (j = 0; j < 3; j++) {
          out += "<td>"+arr[i][j]+"</td>";
        }
        out += "</tr>";
    }
    out += "</table>";
    document.getElementById("JSONtable").innerHTML = out;
}
</script>
user2314737
  • 27,088
  • 20
  • 102
  • 114