(Json with object) Ajax [closed]

1

How can I consume in ajax the following Json (coming from a Rest Web Api?)

    [
     {
      "usuario":       {
         "id": 1,
         "login": "gleyson",
         "senha": "123",
         "ativo": "S"
      },
      "id": 1,
      "tipo": "J",
      "razao_social": "INTELIDER SISTEMAS",
      "nome_fantasia": "INTELIDER SISTEMAS",
      "cpf_cnpj": "0",
      "rg_insc_estadual": "0"
   },
      {
      "usuario":       {
         "id": 2,
         "login": "gleyson",
         "senha": "123456",
         "ativo": "S"
      },
      "id": 2,
      "tipo": "J",
      "razao_social": "INTELIDER",
      "nome_fantasia": "INTELIDER",
      "cpf_cnpj": "0",
      "rg_insc_estadual": "0"
   }
]

The detail is that one of the fields is an object.

    
asked by anonymous 14.06.2017 / 15:15

1 answer

2

To populate a table with this JSON you can loop, like this:

var json = [{
    "usuario": {
      "id": 1,
      "login": "foobar",
      "senha": "123",
      "ativo": "N"
    },
    "id": 1,
    "tipo": "J",
    "razao_social": "INTELIDER SISTEMAS",
    "nome_fantasia": "INTELIDER SISTEMAS",
    "cpf_cnpj": "0",
    "rg_insc_estadual": "0"
  },
  {
    "usuario": {
      "id": 2,
      "login": "gleyson",
      "senha": "123456",
      "ativo": "S"
    },
    "id": 2,
    "tipo": "J",
    "razao_social": "INTELIDER",
    "nome_fantasia": "INTELIDER",
    "cpf_cnpj": "0",
    "rg_insc_estadual": "0"
  }
];

var table = document.querySelector('table');

var linhas = json.reduce(function(html, obj) {
  return [html, '<tr>',
    '<td>' + obj.nome_fantasia + '</td>',
    '<td>' + obj.usuario.login + '</td>',
    '<td>' + obj.usuario.ativo + '</td>',
    '</tr>'
  ].join('');
}, '');
table.innerHTML = linhas;
<table></table>
    
14.06.2017 / 15:41