Print json data received in jquery post

3

I am with the following doubt, I am doing a freight calculation system the system is getting a json answer in the following pattern.

{"cServico":
    [{"Codigo":"40010","Valor":"36,90","PrazoEntrega":"3","ValorSemAdicionais":"36,90","ValorMaoPropria"
    :"0,00","ValorAvisoRecebimento":"0,00","ValorValorDeclarado":"0,00","EntregaDomiciliar":"S","EntregaSabado"
    :"S","Erro":"0","MsgErro":{}},{"Codigo":"41106","Valor":"17,80","PrazoEntrega":"6","ValorSemAdicionais"
    :"17,80","ValorMaoPropria":"0,00","ValorAvisoRecebimento":"0,00","ValorValorDeclarado":"0,00","EntregaDomiciliar"
    :"S","EntregaSabado":"N","Erro":"0","MsgErro":{}}
]}

How can I be displaying this data.

$('body').append(data);

With this code it shows the most accurate array of just some data and I can not thank you in advance.

    
asked by anonymous 09.07.2015 / 14:20

1 answer

5

This JSON must first be converted to Object. You can do this using JSON.parse :

var dados = JSON.parse(data);

Then it depends on how you want to use the data that you have in this property array / key cServico .

I leave an example with a table:

var dados = JSON.parse(data);
var table = document.createElement('table');

// table head
var tr = document.createElement('tr');
Object.keys(dados.cServico[0]).forEach(function (chave) {
    var th = document.createElement('th');
    var tdConteudo = document.createElement('td');
    th.innerHTML = chave;
    tr.appendChild(th);
});
table.appendChild(tr);

// conteudo tabela
dados.cServico.forEach(function (el) {
    var tr = document.createElement('tr');
    Object.keys(el).forEach(function (chave) {
        var tdConteudo = document.createElement('td');
        tdConteudo.innerHTML = el[chave];
        tr.appendChild(tdConteudo);
    })
    table.appendChild(tr);
});
document.body.appendChild(table);

jsFiddle: link

    
09.07.2015 / 14:36