Just change the following line

otArr.push('"' + e + '": {' + itArr.join(',') + '}');

to

otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');

The parenthesis will add the values as numbers not strings.

Also, add keys array for internal object keys.

function html2json() {
   var json = '{';
   var otArr = [];
  // var i = 1;
   var tbl2 = $('table tbody tr').each(function(e) {        
      x = $(this).children();
      var itArr = [];
      var keys = ['no','name','lastname'];
      x.each(function(i) {
         itArr.push('"' + keys[i] + '":"' + $(this).text() + '"');
      });
      otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');
   })
   json += otArr.join(",") + '}'

   return json;
}
Answer from mhatch on Stack Overflow
Top answer
1 of 4
2

Just change the following line

otArr.push('"' + e + '": {' + itArr.join(',') + '}');

to

otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');

The parenthesis will add the values as numbers not strings.

Also, add keys array for internal object keys.

function html2json() {
   var json = '{';
   var otArr = [];
  // var i = 1;
   var tbl2 = $('table tbody tr').each(function(e) {        
      x = $(this).children();
      var itArr = [];
      var keys = ['no','name','lastname'];
      x.each(function(i) {
         itArr.push('"' + keys[i] + '":"' + $(this).text() + '"');
      });
      otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');
   })
   json += otArr.join(",") + '}'

   return json;
}
2 of 4
1

You can convert e to a Number and add one to it like in this fiddle.

function html2json() {
  var json = '{';
  var otArr = [];
  // var i = 1;
  var tbl2 = $('table tbody tr').each(function(e) {
    x = $(this).children();
    var itArr = [];
    x.each(function() {
      itArr.push('"' + $(this).text() + '"');
    });
    otArr.push('"' + (Number(e) + 1) + '": {' + itArr.join(',') + '}');
  })
  json += otArr.join(",") + '}'

  return json;
}

The json you're returning is not valid though. You may want to do something like this fiddle if you can to simplify and ensure valid json and to create your objects from any table structure.

function html2json() {   
  var otArr = [];
  var tblHeaders = Array.from($('table thead tr')
    .children())
    .map(header => $(header).text());  
  var tbl2 = $('table tbody tr').each(function(e) {        
    const values = Array.from($(this).children());
    const row = {};
    for (let i = 0; i < tblHeaders.length; i++){        
        row[tblHeaders[i]] = $(values[i]).text();
    }
    otArr.push({
        [e+1]: row
    })      
  })
  json = JSON.stringify(otArr);  
  return json;
}
🌐
IBM
developer.ibm.com › articles › i-json-table-trs
JSON Format Example: JSON_TABLE function
March 30, 2021 - This article explains the four types of database columns that can be defined using JSON tables, and provides examples of using JSON_TABLE to retrieve JSON objects from the web and process that information in relational form.
🌐
Tabular-json
tabular-json.org
Tabular-JSON: JSON with tables
The data format Tabular-JSON is a superset of JSON, adding CSV-like tables
Top answer
1 of 1
2

There are different options for representing data in JSON (or any format).

Here is an example of one way I would choose to represent the data in the originally posted question:

{   "PHC": [{"CEP": {"Status": "Done", "Notes": "Inspector remarks here"}}],

    "PVC": [{"CFP": {"Status": "Done", "Notes": "Inspector remarks here"},
             "CIL": {"Status": "Done", "Notes": "Inspector remarks here"},
             "CLL": {"Status": "Done", "Notes": "Inspector remarks here"},
             "CPC": {"Status": "Done", "Notes": "Inspector remarks here"},
             "CPQ": {"Status": "Done", "Notes": "Inspector remarks here"},
             "CPS": {"Status": "Done", "Notes": "Inspector remarks here"},
             "CPA": {"Status": "Done", "Notes": "Inspector remarks here"}}],

    "CovTest": [{"FrontCT": {"Status": "Done", "Notes": "Inspector remarks here"}}],

    "OpCheck": [{"": {"Status": "Done", "Notes": "Inspector remarks here"}}]
}

(It's mostly abbreviated, because I wrote this based on the data provided as an image, and I did not want to transcribe everything. Hopefully, you get the idea.)

...

And, this is the exact same JSON (except text is now copied from the updated question), but prettified and validated, using more standard white space formatting:

{
    "Physical check": [{
        "Check existing printer": {
            "Status": "checked",
            "Notes": "Inspector remarks here"
        }
    }],

    "Printer visual check": [{
        "Check front of printer": {
            "Status": "checked",
            "Notes": "Inspector remarks here"
        },
        "Check ink levels": {
            "Status": "checked",
            "Notes": "Inspector remarks here"
        },
        "Check led lights": {
            "Status": "checked",
            "Notes": "Inspector remarks here"
        },
        "Check power cord": {
            "Status": "checked",
            "Notes": "Inspector remarks here"
        },
        "Check print quality": {
            "Status": "checked",
            "Notes": "Inspector remarks here"
        },
        "Check paper size": {
            "Status": "checked",
            "Notes": "Inspector remarks here"
        },
        "Check paper amount": {
            "Status": "checked",
            "Notes": "Inspector remarks here"
        }
    }],

    "Covers test": [{
        "Front cover test": {
            "Status": "checked",
            "Notes": "Inspector remarks here"
        }
    }],

    "Operative check": [{
        "": {
            "Status": "checked",
            "Notes": "Inspector remarks here"
        }
    }]
}
🌐
Datatables
editor.datatables.net › examples › advanced › deepObjects.html
DataTables example - Complex (nested) JSON data source
The columns.data, fields.data and fields.name options can be given as Javascript dotted object notation strings, to be able to read the data required. For example, to get the first name parameter from the above data source object, use users.first_name as is done in the Editor initialisation in this example. This can be exceptionally useful when working with joined tables.
🌐
Oracle
docs.oracle.com › en › database › oracle › oracle-database › 18 › adjsn › creating-a-table-with-a-json-column.html
4 Creating a Table With a JSON Column
If you are sure that your application inserts only well-formed JSON data into a particular column, then consider disabling the check constraint, but do not drop the constraint. ... CREATE TABLE j_purchaseorder (id VARCHAR2 (32) NOT NULL PRIMARY KEY, date_loaded TIMESTAMP (6) WITH TIME ZONE, po_document VARCHAR2 (23767) CONSTRAINT ensure_json CHECK (po_document IS JSON)); Example 4-2 Inserting JSON Data Into a VARCHAR2 JSON Column
🌐
Blue Feather
bluefeathergroup.com › home › docs › accordion tables
The JSON table structure - Blue Feather
September 8, 2020 - Rows are JSON objects which contain the necessary information to make one row in a table. They may also have a childTable object, which would be another table to display as an expandable accordion value. { "childTable": {...}, "class": "someCustomClass", "data": [...] }
Find elsewhere
🌐
MySQL
dev.mysql.com › blog-archive › json_table-the-best-of-both-worlds
MySQL :: JSON_TABLE - The Best of Both Worlds
September 16, 2018 - Using the latest example above, this query will compute the average age of children in each family: ... Here we merge the existing family object with an object constructed from the computed count and average. JSON_ARRAYAGG will then put all the merged objects back into an array. In this blog post, I have shown how you can use JSON_TABLE to perform relational operations on JSON data.
🌐
W3C
w3.org › TR › csv2json
Generating JSON from Tabular Data on the Web
December 17, 2015 - The annotated table generated from parsing the tabular data file and associated metadata is shown below and provides the basis for the conversion to JSON. Show detailed table annotations · Core annotations for the resulting table T, with 9 columns and 3 rows, are shown below: ... The value of the notes annotation has been shortened for clarity in the table above. Annotations for the columns, rows and cells in table T are shown in the tables below: ... In this example, output for column C1 (GID) is not required; note the suppress output annotation on this column.
🌐
Teradata
docs.teradata.com › r › Enterprise_IntelliFlex_VMware › JSON-Data-Type › JSON-Shredding › JSON_TABLE › JSON_TABLE-Examples
JSON_TABLE Examples - Teradata Vantage
Loading application · Promo placeholder · Tracking Consent Teradata.com · Developers · Getting Started · VantageCloud Lake Documentation AI Unlimited All Documentation · Downloads · Community · Teradata Community Technical Medium Blogs Github Stack Overflow · Try for free
🌐
IBM
ibm.com › docs › en › rpa › 21.0.x
JSON to Table
We cannot provide a description for this page right now
🌐
EncodedNA
encodedna.com › javascript › populate-json-data-to-html-table-using-javascript.htm
Dynamically Convert JSON to HTML Table Using JavaScript
Just three records for the example. You can add more. Note: You can also use jQuery to convert data from a JSON file to an HTML table · [ { "Book ID": "1", "Book Name": "Computer Architecture", "Category": "Computers", "Price": "125.60" }, { "Book ID": "2", "Book Name": "Asp.Net 4 Blue Book", "Category": "Programming", "Price": "56.00" }, { "Book ID": "3", "Book Name": "Popular Science", "Category": "Science", "Price": "210.40" } ] ... I want the program to read JSON data, get the columns (Book ID, Book Name etc.) for &lttable> header, and the values for the respective headers.
🌐
Google Cloud
cloud.google.com › bigquery › work with json data in googlesql
Work with JSON data in GoogleSQL | BigQuery | Google Cloud Documentation
bq load --source_format=NEWLINE_DELIMITED_JSON mydataset.table1 file1.jsonl id:INTEGER,json_data:JSON bq show mydataset.table1 Last modified Schema Total Rows Total Bytes ----------------- -------------------- ------------ ------------- 22 Dec 22:10:32 |- id: integer 3 63 |- json_data: json · You can use the Storage Write API (gRPC) to ingest JSON data. The following example uses the Storage Write API (gRPC) Python client to write data into a table with a JSON data type column.
🌐
Medium
rajansahu713.medium.com › select-from-table-to-json-31e1a97c58f2
Select * From Table To JSON. How to JSON Function in SQL | by Rajan Sahu | Medium
September 12, 2024 - A Students table has been made. Let’s add a few records to it now. Converts a PostgreSQL value into its corresponding JSON representation. It is useful when you want to convert individual values (integers, strings, dates) into JSON format. ... Backend and Data Engineer by Day; Teacher, Friend and Content-Writer by night.
🌐
wpDataTables
wpdatatables.com › home › documentation › creating wpdatatables from existing data sources › creating wpdatatables from json input
Creating wpDataTables from JSON input - wpDataTables Tables and Charts Plugin
November 27, 2024 - wpDataTables also supports the JSON format as an input data source. In this example, we will use a sample JSON file with data for 100 imaginary employees. You can download this file for re-use via this link. Let’s view the table first, and then go through the step-by-step tutorial on how to create it.
🌐
Microsoft Learn
learn.microsoft.com › en-us › sql › relational-databases › json › format-query-results-as-json-with-for-json-sql-server
Format Query Results as JSON with FOR JSON - SQL Server | Microsoft Learn
March 12, 2025 - To format the JSON output automatically based on the structure of the SELECT statement, use FOR JSON AUTO. Here's an example of a SELECT statement with the FOR JSON clause and its output.