Html table to json array

Конвертировать HTML Таблица в JSON массив

Подготовьте код HTML Таблица для преобразования в JSON массив. Мы не будем хранить какие-либо ваши данные.

Excel подобный редактору или Builder позволяет легко отредактировать данные HTML Таблица предыдущих данных.

Delete blank rows or columns

Как Конвертировать HTML Таблица в JSON массив онлайн?

1. Загрузить или вставить свой HTML Таблица

Просто вставьте (скопируйте исходный код HTML из браузера) или перетащите файл HTML в TextArea of Источник данных, и он немедленно выполнит магию преобразования. Конвертер Table HTML автоматически ищет таблицы из исходного кода HTML, который вы предоставляете.

2. Отредактируйте свой HTML Таблица онлайн, если это необходимо

Вы можете редактировать свои данные онлайн, например, Excel через Редактор таблицы, а изменения будут преобразованы в JSON массив в режиме реального времени.

3. Скопируйте преобразованный JSON массив

Данные JSON были сгенерированы в поле Генератор таблицы. Этот удобный преобразователь выпускает массив объектов по умолчанию, в дополнение к этому, он также может генерировать различные форматы JSON, таких как 2D массив, массив столбцов и массив клавиш.

Читайте также:  Html растянуть по всей строке

Примечание. Ваши данные безопасны, конверты полностью выполняются в вашем веб-браузере, и мы не будем хранить какие-либо ваши данные.

Что такое HTML?

.htm

HTML Подписчики для гипертекстового языка разметки. HTML — код, который используется для структурирования веб-страницы и его содержимого, абзацев, списка, изображений и таблиц и т. Д.

Что такое JSON?

.json

JSON Подписчики для объекта JavaScript. Файл JSON — это текстовый формат для представления структурированных данных на основе синтаксиса объекта JavaScript.

Источник

Html table to array of json

I have table with dynamic Rows and columns,i was trying to convert HTML table to Json by looping through each tr and td and finding values inside textbox but with no luck.Here is my js code.

 $("#btn_Table2Json").click(function () < var rows = []; $('table.dynatable tbody tr').each(function (i, n) < var $row = $(n); if (n.className.toUpperCase() != "Prototype".toUpperCase() && n.className.toUpperCase() != "Header".toUpperCase()) < $('table.dynatable tbody td').each(function (j, d) < rows.push(< //Here id,Name,Address,Contact are dynamic.so need to find it inside of 'th' of table. //but i am not being able to find it, so i just hard coded it :( Id: $row.find('td:eq(0)').text(), Name: $row.find('td:eq(1)').text(), Address: $row.find('td:eq(2)').text(), Contact: $row.find('td:eq(2)').text() >); >); > >); //debugger; alert(JSON.stringify(rows)); //alert(table.toString()); >); 

TableJson

For above table JSON output should be:

 
ID   Remove Name  Remove Address  Remove Contact  Remove
RemoveRemove-->

3 Answers 3

$('table.dynatable tr').each(function()< rows.push(< Id: $(this).find('td:eq(1) input').val(), Name: $(this).find('td:eq(2) input').val(), Address: $(this).find('td:eq(3) input').val(), Contact: $(this).find('td:eq(4) input').val() >); >); 

my column are also dynamic so can’t hardcode Id,Name,Address,Contact..i have to find column name from th for respective td in $(‘table.dynatable tr’).each(function()<> loop..

Basic Solution — Demo

Because you are using actual input fields, all you really need to do is wrap it in a form. Once you have it as a form, you can select it using jQuery and call serializeArray() to create a name-value array of your inputs.

var table = $('#my_form').serializeArray(); console.log(table); alert(JSON.stringify(table)); 

The result isn’t going to be 100% like you want it. As you can see, all the inputs are in order, but there isn’t a really reliable way to know the difference between the rows. Also, I don’t think order is guaranteed.

Maintain row groupings — Demo

If you edit your named arrays to have the row number, then you’ll be able to know which values belong together. For example, if you had two rows, the input names would look like this:

(notice the name arrays have the row number in it) and the returning results would looks like this:

Massage results into desired output — Demo

Obviously the results still don’t match what you are looking for, but that can be fixed too. We know the name of the field, we know the field’s value, and now we know its row number too. Using some regular expressions, we can separate out the name from the row number. Using a loop we can move things around to a format that we like:

var table = $('#my_form').serializeArray(); var final_results = []; var row_patt = /\[(\d+)\]$/; // Gets the row number inside [] var name_patt = /^[^\[]+/; // Gets the name without the [0] $(table).each( function(index, ele)< // Get the name of input and row number var rowNum = parseInt(row_patt.exec(ele.name)[1]); var name = name_patt.exec(ele.name); // Add the name and value to the correct spot in results if( final_results[rowNum] === undefined )< final_results[rowNum] = <>; > final_results[rowNum][name] = ele.value; >); 

Now we have a nicely formatted array of hashes that list each value per row:

Источник

Html table to json array

Last updated: May 3, 2023
Reading time · 5 min

banner

# Table of Contents

  1. How to convert an HTML table to a JSON array of arrays.
  2. How to convert an HTML table to a JSON array of objects.
  3. How to export the resulting JSON string to a .json file.

# How to convert an HTML table to JSON

To convert an HTML table to JSON:

  1. Store the values of the th elements in an array.
  2. Store the values of the td elements in an array.
  3. Concatenate the two arrays and use the JSON.stringify() method.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div class="box">bobbyhadz.comdiv> br /> br /> br /> table id="my-table"> thead> tr> th>Col 1th> th>Col 2th> th>Col 3th> tr> thead> tbody> tr> td>A1td> td>A2td> td>A3td> tr> tr> td>B1td> td>B2td> td>B3td> tr> tr> td>C1td> td>C2td> td>C3td> tr> tbody> table> script src="index.js"> script> body> html>

example table

And here is the code for the index.js file.

Copied!
function toObject(table) const thead = Array.from(table.tHead.rows[0].children).map( el => el.textContent, ); const tbody = Array.from(table.tBodies[0].rows).map(row => Array.from(row.cells).map(cell => cell.textContent), ); return table: [thead].concat(tbody), thead, tbody, >; > const table = document.getElementById('my-table'); const obj = toObject(table); // 👇️ [['Col 1','Col 2','Col 3'],['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']] console.log(obj.table); // 👇️ ['Col 1', 'Col 2', 'Col 3'] console.log(obj.thead); // [['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']] console.log(obj.tbody); const jsonStr = JSON.stringify(obj.table); // [["Col 1","Col 2","Col 3"],["A1","A2","A3"],["B1","B2","B3"],["C1","C2","C3"]] console.log(jsonStr);

The toObject function converts the table to an object that has 3 properties:

Copied!
// 👇️ [['Col 1','Col 2','Col 3'],['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']] console.log(obj.table);
Copied!
// 👇️ ['Col 1', 'Col 2', 'Col 3'] console.log(obj.thead);
Copied!
// [['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']] console.log(obj.tbody);

If you need to convert any of the properties to JSON, use the JSON.stringify method.

Copied!
const jsonStr = JSON.stringify(obj.table); // [["Col 1","Col 2","Col 3"],["A1","A2","A3"],["B1","B2","B3"],["C1","C2","C3"]] console.log(jsonStr);

# How to convert an HTML table to an Array of Objects

If you need to convert the HTML table to an array of objects:

  1. Get an array of the table’s headings.
  2. Get an array of the table’s rows.
  3. Iterate over the table’s rows and store each heading as a key and the current th text content as the value.

The HTML for the example is the same as in the previous subheading.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div class="box">bobbyhadz.comdiv> br /> br /> br /> table id="my-table"> thead> tr> th>Col 1th> th>Col 2th> th>Col 3th> tr> thead> tbody> tr> td>A1td> td>A2td> td>A3td> tr> tr> td>B1td> td>B2td> td>B3td> tr> tr> td>C1td> td>C2td> td>C3td> tr> tbody> table> script src="index.js"> script> body> html>

Here is the related JavaScript code.

Copied!
function toArrayOfObjects(table) const columns = Array.from(table.querySelectorAll('th')).map( heading => heading.textContent, ); const rows = table.querySelectorAll('tbody > tr'); return Array.from(rows).map(row => const dataCells = Array.from(row.querySelectorAll('td')); return columns.reduce((obj, column, index) => obj[column] = dataCells[index].textContent; return obj; >, >); >); > const table = document.getElementById('my-table'); // [ // // "Col 1": "A1", // "Col 2": "A2", // "Col 3": "A3" // >, // // "Col 1": "B1", // "Col 2": "B2", // "Col 3": "B3" // >, // // "Col 1": "C1", // "Col 2": "C2", // "Col 3": "C3" // > // ] console.log(toArrayOfObjects(table)); const jsonStr = JSON.stringify(toArrayOfObjects(table)); // [,,] console.log(jsonStr);

The toArrayOfObjects() function takes a table element as a parameter and returns an array of objects.

The table headings are used as properties in each object and the text content of the td elements is used as the values.

If you need to convert the array of objects to a JSON string, use the JSON.stringify() method.

# Convert an HTML table to JSON and export it as a JSON file

  1. Converts the HTML table to a JSON array of objects (could be any other data structure).
  2. Exports the JSON to a file.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div class="box">bobbyhadz.comdiv> br /> br /> br /> table id="my-table"> thead> tr> th>Col 1th> th>Col 2th> th>Col 3th> tr> thead> tbody> tr> td>A1td> td>A2td> td>A3td> tr> tr> td>B1td> td>B2td> td>B3td> tr> tr> td>C1td> td>C2td> td>C3td> tr> tbody> table> button id="btn">Click to Download Table as JSONbutton> script src="index.js"> script> body> html>

html table with download as json button

And here is the code for the index.js file.

Copied!
function toArrayOfObjects(table) const columns = Array.from(table.querySelectorAll('th')).map( heading => heading.textContent, ); const rows = table.querySelectorAll('tbody > tr'); return Array.from(rows).map(row => const dataCells = Array.from(row.querySelectorAll('td')); return columns.reduce((obj, column, index) => obj[column] = dataCells[index].textContent; return obj; >, >); >); > const table = document.getElementById('my-table'); function downloadJSONTable(jsonStr, fileName) const dataStr = `data:text/json;charset=utf-8,$encodeURIComponent( jsonStr, )>`; const anchorElement = document.createElement('a'); anchorElement.href = dataStr; anchorElement.download = `$fileName>.json`; document.body.appendChild(anchorElement); anchorElement.click(); document.body.removeChild(anchorElement); > const downloadButton = document.getElementById('btn'); downloadButton.addEventListener('click', () => const jsonStr = JSON.stringify(toArrayOfObjects(table)); downloadJSONTable(jsonStr, 'myFile'); >);

Here are the contents of the exported .json file.

contents of exported json file

The downloadJSONTable function takes a JSON string and the name the downloaded file should have on the user’s file system as parameters and exports the supplied JSON string to a file.

The file is a bit difficult to read because it only consists of a single line, however, you could pretty print the JSON by passing a third argument to the JSON.stringify() method.

Copied!
const jsonStr = JSON.stringify( toArrayOfObjects(table), null, 2, );

export json table pretty print

The third argument is the indentation of the JSON string.

The new JSON string is much more readable as each key-value pair is displayed on a separate line.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • Download Images using JavaScript (Local and from URL)
  • How to fetch Data on Button click in React
  • TypeError: Failed to fetch and CORS in JavaScript [Solved]
  • fetch() returns empty Response Body in JavaScript [Solved]
  • How to Use an Image as a Link in React.js
  • Import and use an Image in a React component
  • Add an on Click event to Table Rows in JavaScript
  • How to wrap the content of a table cell using CSS
  • Resource interpreted as stylesheet but transferred with MIME type text/html
  • How to put an Input element on the same line as its Label
  • How to export an HTML table to Excel using JavaScript
  • [DOM] Input elements should have autocomplete attributes

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью