Javascript does not recognize Json

0

I have the following idea that the moderator Sergio sent

var obj = [JSON]

var mydiv = document.getElementById("tabLista");
mydiv.innerHTML = "";
var ul = document.createElement("ul");
mydiv.appendChild(ul);

var escolhidas = [];
obj.forEach(function(obj) {
  obj = obj.List;
  var li = document.createElement("li");
  ul.appendChild(li);
  Object.keys(obj).forEach(function(chave) {
    var div = document.createElement("div");
    div.classList.add(chave);
    div.textContent = obj[chave];
    li.appendChild(div);
  });
  var checkbox = document.createElement("input");
  checkbox.type = 'checkbox';
  checkbox.addEventListener('change', function() {
    this.closest('li').classList.toggle('selecionado', this.checked);
    if (this.checked) escolhidas.push(obj);
    else escolhidas = escolhidas.filter(function(el) {
      return el != obj;
    });
    console.log(escolhidas);
  });
  li.appendChild(checkbox);
});

Only when I enter json that my server responds the script does not recognize the keys, it only prints

[object Object]
[object Object]
[object Object]

Json that my server responds

{
    "api": "api",
    "List": [{
        "tipo": "1",
        "data": "10/10/2017",
        "Hora": "11:38",
        "Size": "0",
        "Nome": "Marcelo"
    }, {
        "tipo": "1",
        "data": "10/10/2017",
        "Hora": "11:38",
        "Size": "0",
        "Nome": "Pedro"
    }, {
        "tipo": "1",
        "data": "10/10/2017",
        "Hora": "11:38",
        "Size": "0",
        "Nome": "Lucas"
    }],
    "arq": "1",
    "paste": "2"
}

Json From the original idea

var obj = [{
    nome: 'a',
    data: '13/09/2017'
  },
  {
    nome: 'b',
    data: '13/09/2017'
  },
  {
    nome: 'c',
    data: '13/09/2017'
  },
  {
    nome: 'd',
    data: '13/09/2017'
  },
]

Obtained:)

    
asked by anonymous 09.10.2017 / 22:12

1 answer

1

The JSON you receive from the server is an object:

{
    "api": "api",
    "List": [{

and .forEach works on arrays. So you have to pass .List directly because .List is an array.

var obj = JSON.parse(req.responseText);

var mydiv = document.getElementById("tabLista");
mydiv.innerHTML = "";
var ul = document.createElement("ul");
mydiv.appendChild(ul);

var escolhidas = [];
obj.forEach(function(obj) {
  // obj = obj.List; // <--- tira isto. Isto era util caso 'obj' fosse uma array.
  var li = document.createElement("li");
  ul.appendChild(li);
  Object.keys(obj).forEach(function(chave) {
  // etc...
    
10.10.2017 / 07:37