Read JSON file by Javascript

Asked

Viewed 4,213 times

0

I need to read a JSON file by 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);
}
  • In all the examples I’ve seen in other questions, they use the following syntax "$. getJSON('ajax/test.json', Function(data) {", but how would I call this function? I just want to execute the reading function of my code.

  • This function is native to Jquery. You use jquery in your project?

  • I do not use Jquery.

1 answer

1


You will need to request your json using the object Xmlhttprequest thus below:

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();

Then the object analyzes the return of the request made by the object Xmlhttprequest and checks that the httpd status is valid (200) and transforms the return of the file (string) to a json using the javascript function 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 serves to execute the code after the page load is complete.

  • I didn’t understand how and when to perform this function. For example, if I want to run when the page loads?

  • First you had set in your html tag body: <body ... onload="load()"> in onload to call the load function but it does not exist, which causes an error in your page, remove the call from its load() function, because I demonstrated how to do this via javascrip with window.onload. As you make a GET to xmlhttp.open("GET", "json/test.json", true); but the file is not on the server responds 404.

  • Oops... that’s right. I fixed these bugs, but it still doesn’t work.

  • Your json is now error =P : VM523:2 Uncaught Syntaxerror: Unexpected token { in JSON at position 2942. Open Chrome and press F12 console tab and look at the errors that appear.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.