Convert JSON to Array in Javascript

Asked

Viewed 4,267 times

5

Good afternoon, it’s my first question here.

I’m getting the json below through an ajax request.

[
    {"SEMANA":1.0,"PRODUCAO":0.0,"PRODUCAO2":0.0},
    {"SEMANA":2.0,"PRODUCAO":29280.0,"PRODUCAO2":55992.0},
    {"SEMANA":3.0,"PRODUCAO":93864.0,"PRODUCAO2":75072.0},    
    {"SEMANA":4.0,"PRODUCAO":135625.0,"PRODUCAO2":102480.0}
]

I convert JSON to array this way below:

$.get("caminho do WebService", function (dados) {
    var arrSemana = [],
    arrProd1 = [],
    arrProd2 = [];
    for (var i = 0; i < dados.length; i++) {
        arrSemana.push(dados[i].SEMANA);
        arrProd1.push(dados[i].PRODUCAO);
        arrProd2.push(dados[i].PRODUCAO2);
    }
    //......
});

Just as soon as I check this one array (arrSemana, arrProd1, arrProd2) gets like this [,,,,,,,,] and not with the values as I would like [1.0, 2.0, 3.0]

I’m creating graphics with the highChart so I need that array.

Where am I wrong that he’s not taking the values as I need them? Does anyone have an example that can help me?

Thank you all for your attention.

I am working with Apache Cordova (Phonegap). I need to put this in 3 array so I can put it on the chart.

$(Function () { $.get("Webservice path", Function (data) {

var arrSemana = [],
    arrProd1 = [],
    arrProd2 = [];

for (var i = 0; i < dados.length; i++) {
    arrSemana.push(dados[i].SEMANA);
    arrProd1.push(dados[i].PRODUCAO);
    arrProd2.push(dados[i].PRODUCAO2);
}
// Os alerts estão aqui para teste...
alert(dados);
alert(arrSemana);
alert(arrProd1);
alert(arrProd2);

$('#chart').highcharts({
    title: {
        text: 'Produção semanal de açúcar (registrada)',
        x: -20 //center
    },
    subtitle: {
        text: 'Dados: Teste de Relatório',
        x: -20
    },
    xAxis: {
        title: {
            text: 'Semanas'
        },
        categories: arrSemana, //Um array vem aqui...
        minTickInterval: 5,
        minRange: 0,
        min: 0
    },
    yAxis: {
        allowDecimals: false,
        title: {
            text: 'Produção'
        },
        plotLines: [{
            value: 0,
            width: 1,
            color: '#808080'
        }]
    },
    tooltip: {
        valueSuffix: 'un'
    },
    legend: {
        layout: 'vertical',
        align: 'middle',
        verticalAlign: 'bottom',
        borderWidth: 0
    },
    series: [{
        name: 'Semanas 12/13',
        color: '#32CD32',
        data: arrProd1 // Outro array vem aqui...
    }, {
        name: 'Semanas 13/14',
        color: '#000000',
        data: arrProd2 // Outro array vem aqui...
    }]
});

}).fail(Function() { Alert("Error loading report data."); }); });Essa imagem foi gerada fazendo o exemplo explicado abaixo...

  • you cannot send the array in the correct format?

  • But the array is what I’m unable to mount. Did you talk about JSON will be? .

  • 1

    Is the return type (mimetype, contenttype) correct? If you call get without specifying a dataType jQuery "guesses" the correct format based on server return. You can use getJSON also. Other than that, your code seems correct. Have you ever tried to do console.log(dados) and see if everything is ok?

  • I already used $.getJSON and it happened the same thing, so I did it this way to test if it would be different the result.

  • Your password is correct; http://jsbin.com/layojiqahu/1/edit?js,console da um console.log no dados and see if it is returning correct from the server

  • Poise I also tested the code and it seems correct: http://jsfiddle.net/3s8mrcb3/

  • @Rafaeloliveira If the code is correct and the type is correct, either the problem is in the data or it’s time for you use the values. If the console.log do not show anything abnormal, please post the code where you use these arrays.

  • So that’s what struck me, too. Then I got confused, because it seems right. You have some other idea of how to put this together?

  • I am leaving now, I will be tomorrow and return here the result. Thank you for now.

  • @mgibsonbr posted my code here...as I am working with Apache Cordova (phonegap) I am not able to test the console.log, I can only emulate via device.

Show 5 more comments

1 answer

5


I suggest using the .map() to do this.

var json = JSON.parse('[ {"SEMANA":1.0,"PRODUCAO":0.0,"PRODUCAO2":0.0}, {"SEMANA":2.0,"PRODUCAO":29280.0,"PRODUCAO2":55992.0}, {"SEMANA":3.0,"PRODUCAO":93864.0,"PRODUCAO2":75072.0}, {"SEMANA":4.0,"PRODUCAO":135625.0,"PRODUCAO2":102480.0} ]');

var arrays = ['SEMANA','PRODUCAO','PRODUCAO2'];
arrays = arrays.map(function(campo){
    var novoConteudo = json.map(function(objeto){
       return objeto[campo]; 
    });
    return novoConteudo;
});

alert(JSON.stringify(arrays));

The .map() part of an array and returns an array with the same number of elements but with new content. So starting from ['SEMANA','PRODUCAO','PRODUCAO2'] made a first map() iterates each field, within the first map I create another map, which iterates the JSON. So for each JSON array I will only get the "field" that interests me.

Note that in your JSON some fields come for example 1.0 numeric. If you don’t have this in String then it will be read as only 1.


If you want to have a variable for each array you can do:

var arrSemana = arrays[0];
var arrProd1 = arrays[1];
var arrProd2 = arrays[2];
  • But I need these 3 arrays to assemble the graph according to the complete code I posted below, so it seems that everything will be in just one array. That’s right?

  • @Rafaeloliveira I ran the example of Sergio, and here appeared the 3 arrays you need, straight. The 3 are available within the variable arrays. Then it did not give the same result?

  • I tested here, it did return the 3 arrays inside a hair it seems. How now do I select only the one I wish to put each of the 3 in their place? As the code I showed above I use it in highchart, and then in it I pass these array. I have an image of Alert shown on android, where I can add to stay example?

  • I added an image of the example obtained in the first question I asked above.

  • The 3 arrays you want: arrays[0], arrays[1] and arrays[2] ...

  • @Rafaeloliveira I added an example at the end of the answer.

Show 1 more comment

Browser other questions tagged

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