(json with object) ajax

Asked

Viewed 61 times

1

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

    [
     {
      "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.

  • How do you want to use this JSON? create HTML with it or just fetch a specific value?

  • @Sergio, as the relationship 1 = 1 wanted to know how to put in a table for example: name_fantasia, login, active.

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>

  • 1

    that’s what I needed, thank you

Browser other questions tagged

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