How I Store the Contents of a JSON File in a Variable

Asked

Viewed 549 times

0

agenda=[];
$.getJSON("agenda.json", function(dados) {
 agenda=dados;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • 1

    What is the problem with the code? The answer "does not work" or variations of it are not accepted. Describe what is happening and what is your difficulty. Have you read the documentation of getJSON? And already made the [tour] on the site?

  • 1

    Do not store. Use the data inside that function (callback). Or call another function from there and pass the die on. But do not assign it to an outside variable. It will be filled in, but not immediately (the operation is asynchronous). And you’re probably trying to use it before the time.

1 answer

0

I used the jqxhr Object example from the following link http://api.jquery.com/jquery.getjson/

About the mistake, I think you missed declare the variable formerly.

    //agenda = [];
    //$.getJSON("http://echo.jsontest.com/key/value/one/two", function(dados) {
    //  agenda = dados;
    //});

    // Atribua manipuladores imediatamente após fazer o pedido,
        // e lembre-se do objeto jqxhr para este pedido
    var jqxhr = $.getJSON( "http://echo.jsontest.com/key/value/one/two", function(dados) {
      console.log( "Sucesso" );
      console.log(dados);
      console.log("Primeiro dado:"+dados.one+"\nSecond data:"+dados.key);
    })
      .done(function() {
        console.log( "Segundo sucesso" );
      })
      .fail(function() {
        console.log( "Error" );
      })
      .always(function() {
        console.log( "Completo" );
      });

    // Execute outro trabalho aqui ...

    // Defina outra função de conclusão para o pedido acima
    jqxhr.complete(function() {
      console.log( "Segundo completo" );
    });

    //console.log(agenda);
    console.log("### - @lucaslimax, @lucaslimay or [email protected] good life!");

    // Link da documentação
    // ## - http://api.jquery.com/jquery.getjson/

    // Link do arquivo .json vindo de uma api de test
    // ## - http://echo.jsontest.com/key/value/one/two
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I hope it helped.

  • I also advise you to read this question here https://answall.com/questions/63685/colocar-valor-json-na-variavel?rq=1

  • 1

    You can translate the comments in the code?

  • @Sergio I translated the comments ;-)

Browser other questions tagged

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