How to show values stored in JSON in Javascript

Asked

Viewed 10,027 times

4

Has a variable in a file JSON which is called "valore" and it is assigning the values:2.51,2.56,2.87,2.89 and 2.94. The string of this JSON is being displayed in a DIV. How do I show only these values?

  • Show values inside the div? You can assign a ID to div and do something like: document.getElementById("div_id").innerHTML = valore;

  • @Pedrohenrique The numbers of which written above formed a graph. I have tried to use this command but unfortunately it doesn’t work...

  • Do you use any library to form this chart? Can explain better where you want to show the values and how you want to show the values?

  • Can you show exactly how the data is? Put console.log(valore) and take the result of your browser console.

  • Yes I use the Rgraph to copm it to make the graph, I want to show those values in a variable in the html page... because the graph is already ready and I have to get this values from the automatic server.

  • What you want is to take the values of a JSON, not the JSON variable.

Show 1 more comment

3 answers

1

Your question is not very explanatory, but I will try to help you with what I understand...

Good first you have to "take" this JSON, so you take it you will have 1 JSON object in your hand. To treat this object you need to go through each of its attributes and display only those that interest you, I’ll show you a code I made these days for a similar goal.

$.ajax({
    type: 'GET',
    url: "ENDEREÇO DO SEU JSON",
    dataType: 'json',
    contentType: 'application/json',
    crossDomain: true,
    cache:false,
    success: function(data) 
    {
        $.each(data, function(i, desafio) {
            item = "<center><h4>" + desafio.meta + "</h4></center>";

            if (desafio.id == $('#selectDesafio').val() ) {
                $('#blocodesafio').html(''),
                $('#blocodesafio').append(item);
            }
        });
    },
    error:function(jqXHR, textStatus, errorThrown){
        alert('Erro ao carregar');
        console.log(errorThrown);
    }
}); 

In this code I selected each Goal of my challenge and assigns according to the value of my selectDesafio. I hope it helps you.

1

It depends a lot on how this data is archived in this JSON. For example, it may exist like this:

{ valore: [ 2.51, 2.56, 2.87, 2.89, 2.94 ] }

If it is, putting that value on a <div> may not show exactly what you want. In this case, using jQuery, you can make a $.each(), thus:

var html = "";
$.each(valore, function(i) {
   html = i + ', ' + html;
});
$('#idDoDiv').html(html);

0

To access a value from your JSON object:

var dados = { valore: [ 2.51, 2.56, 2.87, 2.89, 2.94 ] };

//aqui vc está pegando o primeiro valor
dados.valore[0];
//também pode ser acessado assim:
dados['valore'][0];

To get the whole string, you can simply concatenate everything using Join with its concatenator, since it is an array:

dados.valore.join(",");

Or make a simple for:

for (var i in dados.valore) {
     console.log(dados.valore[i]); //envia pro console o valor
}

To handle a POST output of the object:

Before sending to a variable, you need to parseJSON, in pure javascript it would be JSON.parse(data), but jQuery has a method that makes a more elaborate treatment:

$.post('/url_enviada', function(data) {
         //retorno dos dados-> data
          var dados = jQuery.parseJSON(data);
          console.log(dados.valore.join("\n"));
});

There are other not very recommended ways for you to parse the JSON object:

var dados = eval('(' + data + ')');

or

var dados;
eval('dados = ' + data);

And if your method is an ajax, already informing the type of expected data, it is not necessary to parse, it internally is already returning you object, when you inform the type of dataType:

  $.ajax({ 
         type: 'POST', //método POST, GET, PUT...
         url: "url_enviada", //url que irá construir o json_encode()
         dataType: 'json', //aqui ele define o tipo de dado esperado
         contentType: 'application/json', //para converter a saída em utf-8
         crossDomain: true, //para não ter bloqueio de crossDomain
         cache:false //para não fazer cache
         }) //promises
        .done(function(data) {
         $( "#element_div" ).html( data.valore[0] +'<br>' + data.valore[1] );
         })
        .fail(function() {
         $( "#element_div" ).html( "erro no processo!" );
         }) 
        .always(function() {
         })
        .then(function() {
         });
  • I believe it’s safe to use the JSON.parse, After all even IE8 supports it (source: ca i use). the jQuery.parseJSON basically checks whether the JSON.parse is available if you are not using a eval(). I always want to put the following content in the pages I write: <!--[if lte IE 8]><meta http-equiv="refresh" content="0;url=http://outdatedbrowser.com/pt" /><![endif]-->

Browser other questions tagged

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