How to show values stored in JSON in JavaScript

4

It has a variable in a file JSON that is called "value" 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 DIV . How do I show only those values?

    
asked by anonymous 16.03.2015 / 15:22

3 answers

1

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

Well first you have to "get" this JSON, as soon as you get 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 purpose.

$.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 have selected each Goal from my challenge and assign it according to the value of my select Challenge. I hope it helps you.

    
17.03.2015 / 13:07
1

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

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

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

var html = "";
$.each(valore, function(i) {
   html = i + ', ' + html;
});
$('#idDoDiv').html(html);
    
22.07.2015 / 00:58
0

To access a value of 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 your 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 do a parseJSON, in pure javascript it would be JSON.parse(data) , however jQuery has a method that does 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 ways you can not parse the JSON object:

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

or

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

And if your method is an ajax, already informing the expected data type, 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() {
         });
    
28.10.2015 / 13:08