Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert the following table to JSON with javascript?

How to make the following table into a JSON string in jquery/javascript?

<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A1</td>
      <td>A2</td>
      <td>A3</td>
    </tr>
    <tr>
      <td>B1</td>
      <td>B2</td>
      <td>B3</td>
    </tr>
    <tr>
      <td>C1</td>
      <td>C2</td>
      <td>C3</td>
    </tr>
  </tbody>
</table>

I want to make it such that I can get a JSON string in a variable "myjson" that could be used in a POST request or GET request:

{
  "myrows" : [
    {
      "Column 1" : "A1",
      "Column 2" : "A2",
      "Column 3" : "A3"
    },
    {
      "Column 1" : "B1",
      "Column 2" : "B2",
      "Column 3" : "B3"
    },
    {
      "Column 1" : "C1",
      "Column 2" : "C2",
      "Column 3" : "C3"
    }
  ]
}

What is the best way to accomplish this? (Note: There may be a varying number of rows, I just want to extract the text while ignoring the other tags inside of the table)

like image 693
Rolando Avatar asked Mar 29 '12 14:03

Rolando


People also ask

How do you convert JavaScript data into JSON?

JSON.stringify() The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

How do you convert Excel to JSON using JavaScript?

In JavaScript we can add the event listeners to elements like this: We can read the data in the excel file by using a file reader as a binary string in JavaScript. Then we use XLSX which has a built-in facility of SheetJS to convert our binary string into a JSON object.

Can we convert JSON to table?

Yes, ImportJSON is a really easy tool to use for taking information from JSON and putting it into a table or spreadsheet. Including if you want to parse your JSON directly from Google Sheets!


4 Answers

Update: There's a slightly improved fork of the solution (below) on jsFiddle.

You just need to walk the DOM of your table reading it out... this is not even close to optimized but will give you the result you want. (jsFiddle)

// Loop through grabbing everything
var myRows = [];
var $headers = $("th");
var $rows = $("tbody tr").each(function(index) {
  $cells = $(this).find("td");
  myRows[index] = {};
  $cells.each(function(cellIndex) {
    myRows[index][$($headers[cellIndex]).html()] = $(this).html();
  });    
});

// Let's put this in the object like you want and convert to JSON (Note: jQuery will also do this for you on the Ajax request)
var myObj = {};
myObj.myrows = myRows;
alert(JSON.stringify(myObj));​

And the output...

{"myrows":[{"Column 1":"A1","Column 2":"A2","Column 3":"A3"},{"Column 1":"B1","Column 2":"B2","Column 3":"B3"},{"Column 1":"C1","Column 2":"C2","Column 3":"C3"}]}
like image 167
scottheckel Avatar answered Oct 05 '22 19:10

scottheckel


I needed the same thing except with the ability to ignore columns, override values, and not be confused by nested tables. I ended up writing a jQuery plugin table-to-json:

https://github.com/lightswitch05/table-to-json

All you have to do is select your table using jQuery and call the plugin:

var table = $('#example-table').tableToJSON();

Here is a demo of it in action:

http://jsfiddle.net/nyg4z/27/

like image 34
lightswitch05 Avatar answered Oct 05 '22 21:10

lightswitch05


Here is a solution without jQuery, inspired by this article:

function tableToJson(table) { 
    var data = [];
    for (var i=1; i<table.rows.length; i++) { 
        var tableRow = table.rows[i]; 
        var rowData = []; 
        for (var j=0; j<tableRow.cells.length; j++) { 
            rowData.push(tableRow.cells[j].innerHTML);; 
        } 
        data.push(rowData); 
    } 
    return data; 
}
like image 6
Basj Avatar answered Oct 05 '22 20:10

Basj


My version of it:

var $table = $("table"),
    rows = [],
    header = [];

$table.find("thead th").each(function () {
    header.push($(this).html());
});

$table.find("tbody tr").each(function () {
    var row = {};

    $(this).find("td").each(function (i) {
        var key = header[i],
            value = $(this).html();

        row[key] = value;
    });

    rows.push(row);
});

See the Fiddle.

like image 4
alextercete Avatar answered Oct 05 '22 21:10

alextercete