JSON file reading by JavaScript

0

I need to read a JSON file through JavaScript and assign each item of it to a single variable, as I did in this algorithm:

function leitura(){
   var arquivo = **Ler arquivo**('json/teste.json');
   var conteudo;
   **Laço de repetição**{
       conteudo += arquivo.nome + ', ';
   }
   alert(conteudo);
}
    
asked by anonymous 26.12.2017 / 12:36

1 answer

1

You will need to place a request for your json using the XMLHttpRequest object as follows:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       var myObj = JSON.parse(this.responseText);
       document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();

Next, the object parses the return of the request made by the XMLHttpRequest object and verifies that the status httpd is valid (200) and transforms the return of the file (string) to a json using the function javascript JSON.parse , then you can read the json entries one by one to your variable as you did above in your example.

Deepen your knowledge here: read Json with javascript

To run when the page loads you have to use an event, like this:

window.onload = function(){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {
           var myObj = JSON.parse(this.responseText);
           document.getElementById("demo").innerHTML = myObj.name;
       }
   };
   xmlhttp.open("GET", "json_demo.txt", true);
   xmlhttp.send();
}

window.onload is used to run the code after page load is complete.

    
26.12.2017 / 13:08