2012-03-29 14 views
9

¿Cómo hacer la siguiente tabla en una cadena JSON en jquery/javascript?¿Cómo convertir la siguiente tabla a JSON con 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> 

quiero que sea tal que pueda obtener una cadena JSON en un "myjson" variable que podría ser utilizado en una petición POST o GET solicitud:

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

¿Cuál es la mejor manera de ¿para lograr esto? (Nota: Puede ser un número variable de filas, sólo quiero para extraer el texto sin tener en cuenta las otras etiquetas dentro de la tabla)

+0

puede darnos algunos html por lo que será fácil de escribir el jQuery para que coincida con él! – Michael

+0

¿Cómo se conecta jQuery a su base de datos? (Esto no sería imposible, pero sería improbable.) – TRiG

+0

él dice solicitudes POST y GET que harían esto una conexión ajax obvia (php o aspx) – Michael

Respuesta

20

Actualización: Hay una slightly improved fork of the solution (below) on jsFiddle.

Solo tiene que caminar el DOM de su mesa para leerlo ... esto es ni siquiera cerca de optimizado, pero le dará el resultado que desea. (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));​ 

Y la salida ...

{"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"}]} 
+0

Wow, esto es bueno. Lo acabo de leer. Estoy impresionado. :) – Michael

+0

El único "problema" aquí es que obtienes el valor del encabezado en cada fila. Podrías haberlo guardado en caché. – alextercete

+0

Sí, esa es una de las razones por las que mencioné que no está optimizado. Lo modificaré un poco por eso. – scottheckel

0

Aquí tiene http://jsfiddle.net/Ka89Q/4/

var head = [], 
    i = 0, 
    tableObj = {myrows: []}; 
$.each($("#my_table thead th"), function() { 
    head[i++] = $(this).text(); 
}); 

$.each($("#my_table tbody tr"), function() { 
    var $row = $(this), 
     rowObj = {}; 

    i = 0; 
    $.each($("td", $row), function() { 
     var $col = $(this); 
     rowObj[head[i]] = $col.text(); 
     i++; 
    }) 

    tableObj.myrows.push(rowObj); 
}); 

alert(JSON.stringify(tableObj)); 
2

probar esto.

var myRows = { myRows: [] }; 

var $th = $('table th'); 
$('table tbody tr').each(function(i, tr){ 
    var obj = {}, $tds = $(tr).find('td'); 
    $th.each(function(index, th){ 
     obj[$(th).text()] = $tds.eq(index).text(); 
    }); 
    myRows.myRows.push(obj); 
}); 
alert(JSON.stringify(myRows)); 

demostración de trabajo - http://jsfiddle.net/u7nKF/1/

1

Mi versión de la misma:

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); 
}); 

Véase el Fiddle.

+0

Gracias! Me ayudó mucho porque se separó de $ table, que en mi caso era necesario ya que estoy analizando una cadena de html generada por wordpress (no me pregunte por qué ¬¬) – Cyberdelphos