N
N
narem2019-12-13 10:54:13
JavaScript
narem, 2019-12-13 10:54:13

How to make JSON from a table?

<table id="print-table">
                <tbody><tr class="main-head-table">
                  <th>ФИО</th>
                  <th>Должность</th>
                  <th>Внутренний номер</th>
                </tr>
              <tr>
                  <td colspan="7" style="text-align: center; font-weight: bold;" class="hide-tr">Администрация</td>
                </tr><tr>
                  <td>wer</td>
                  <td>sdf</td>
                  <td>10001</td>
                </tr><tr>
                  <td>sdf</td>
                  <td>sdf</td>
                  <td>10002</td>
                </tr>
                </tr></tbody></table>

How to make this json
someJSONdata = [
{
name: 'John Doe',
rank: '[email protected]',
phone: '111-111-1111'
},
{
name: 'Barry Allen',
rank: ' [email protected]',
phone: '222-222-2222'
},
{
name: 'Cool Dude',
rank: '[email protected]',
phone: '333-333-3333'
}
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NyoNor, 2019-12-13
@narem

Without jquery:

function tableToJson() {
  let result = [];
  let table = document.getElementById("print-table").getElementsByTagName("tbody")[0];
  let trs = table.getElementsByTagName("tr");
  for (let i = 2; i < trs.length; i++) {
    let tds = trs[i].getElementsByTagName("td");
    let obj = {};
      obj.name = tds[0].innerHTML;
      obj.rank = tds[1].innerHTML;
      obj.phone = tds[2].innerHTML;
      result.push(obj);
  }
  return JSON.stringify(result);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question