read JSON file with JS

Asked

Viewed 259 times

0

have this the following JSON file with the name test.json:

"registro":[
{"cnpj":"46148234000117","serie":"1","numero":"1"},
{"cnpj":"46148264000117","serie":"1","numero":"2"},
{"cnpj":"46148224000117","serie":"1","numero":"3"},
{"cnpj":"46148274000117","serie":"1","numero":"4"},
{"cnpj":"46148294000117","serie":"1","numero":"5"},
{"cnpj":"46148204000117","serie":"1","numero":"6"},
{"cnpj":"46148294000117","serie":"1","numero":"7"},
{"cnpj":"46148244000117","serie":"1","numero":"8"},
{"cnpj":"46148247000117","serie":"1","numero":"9"},
{"cnpj":"46148242000117","serie":"1","numero":"10"},

];

and I have this JS function:

$.getJSON("teste.json", function( data ) {
var registro = data.registro;

$.each(data, function(cnpj, numero){
  registro.push("<li id='" + cnpj +"'>"+ numero + "</li>");
});

$("<ul/>", {
  "class": "my-new-list",
  html: registro.join("")
}).appendTo("body");


});

I would like to list exactly how it is in the file, but I don’t know where is the error in my function

  • the error occurs where? " $. getJSON("test.json", Function( date )" ?

  • likely, because it’s showing nothing

  • I believe I must create a loop of repetition

  • and then I need to check if you skipped a number

  • I put an answer, then check it.

1 answer

0


From what I’ve seen, one problem is in this "each"

  var li = [];
  $.each(registro, function(index, value) { // aqui deveria ser "registro" em vez de "data"
    li.push("<li id='" + value.cnpj + "'>" + value.numero + "</li>"); // push no "li" em vez de "registro"
  });

I changed a little and put in the plunker (put, as an example, using reduce too), take a look:

https://plnkr.co/edit/vmSFYK?p=preview

  • good, I think I’ll create a table, and change the append to table

  • in case would have to change the li to <td> ?

  • I switched to the next

  • var li = []; $.each(record, Function(index, value) { // here should be "record" instead of "data" li.push("<li id='" + value.cnpj + "'>" + value.numero + "</li>"); li.push("<tr>"); li.push("<td id='"+key+">"+value.cnpj+"</td>"); li.push("<td id='"+key+">"+.numero+"</td>"); li.push("<td id='"+key+"'>"+val.serie+"</td>"); li.push("</tr>"); // push on "li" instead of "record" });

  • yes, instead of <li> would be <td>, it succeeded ?

Browser other questions tagged

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