Javascript – How to convert the following table to JSON with javascript


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

      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>

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)

Best Solution

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;

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"}]}