Convert a HTML table to JSON. Actually, to an array of JSON objects.
const { res } = document
.getElementById('tableID')
.jsonify();
Consider a HTML table with id=myTable
.
<table id="myTable">
...
</table>
To convert it to an array of JSON objects:
const table = document.getElementById('myTable');
const obj = table.jsonify();
const result = obj.res; // Array of objects.
jsonify
only works on table (HTMLTableElement
).
In the above example, obj
contains following data members:
error
— a flag which indicates if an error was occurred. It isfalse
if no errors occurred, else contains the error message.res
— the array containing JSON objects.headers
— the keys in the objects (also, the table headers).
const table = document.getElementById('tableID');
const obj = table.jsonify();
if (!obj.error) {
// obj.res...
}
- There are no rows in the table.
- Headers repeat.
<td>
has more than one child nodes.
Use this for the client-side JavaScript. Though this module is published as a Node Package Module, it can not run on server-side JavaScript. This is because it makes use of document
, which is not available in Node, as is.
To add it in the <script>
tag, make use of Unpkg.
Example: <script src="unpkg.com/jsonify-my-table@latest/jsonify-my-table.min.js"></script>