jsonify-my-table

Convert a HTML table to JSON
git clone http://git.hanabi.in/repos/jsonify-my-table.git
Log | Files | Refs | LICENSE

jsonify-my-table.js (1481B)


      1 HTMLTableElement.prototype.jsonify = function() {
      2   const result = {};
      3   result["error"] = false;
      4   // 1. Does table have rows?
      5   if (this.rows.length < 1) {
      6     result["error"] = "There are no rows in the table.";
      7     return result;
      8   }
      9 
     10   // 2. Extract headers.
     11   const headers = [...this.rows[0].cells].map(cell => {
     12     if (cell.childElementCount == 0) return cell.innerText;
     13     if (cell.childElementCount != 1) {
     14       result["error"] = "Can't extract headers.";
     15       return undefined;
     16     }
     17     while (cell.childElementCount == 1) cell = cell.children[0];
     18     return cell.innerText;
     19   });
     20 
     21   // 3. Are headers unique?
     22   if (headers.length > new Set(headers).size) {
     23     result["error"] = "Headers repeat";
     24     return result;
     25   }
     26 
     27   // 4. Prepare the result.
     28   const res = [...this.rows].map((row, index) => {
     29     if (index == 0) return; // This is header
     30     const cells = [...row.cells].map(cell => {
     31       if (cell.childElementCount == 0) return cell.innerText;
     32       if (cell.childElementCount != 1) {
     33         result["error"] = "Can't extract information.";
     34         return undefined;
     35       }
     36       while (cell.childElementCount == 1) cell = cell.children[0];
     37       return cell.innerText;
     38     });
     39     return headers.reduce(
     40       (acc, cur, index) => (acc = { ...acc, [cur.valueOf()]: cells[index] }),
     41       {}
     42     );
     43   });
     44 
     45   res.shift(); // Remove header
     46   result["res"] = res;
     47   result["headers"] = headers;
     48   return result;
     49 };
     50 
     51 if (!window) module.exports = jsonify;