How to convert a table to JSON (or to Java array)

P

phil.swenson

I'm using Prototype.js and would like to convert the contents of an
HTML table to JSON. Converting to an array first is fine too. Any
thoughts on this? I haven't seen anyone do anything this....

thanks
phil
 
R

RobG

I'm using Prototype.js

If you want help specifically with Prototype.js, ask on the Ruby on
Rails spinoffs group.

and would like to convert the contents of an
HTML table to JSON. Converting to an array first is fine too. Any
thoughts on this? I haven't seen anyone do anything this....

Sounds fairly trivial. If by "content" you mean text content, loop
over the rows and create one array for each, stuff the contents of
each cell into a row array element and return it as a JSON formatted
text string, e.g.

function table2JSON (t)
{
function getText(el){
if (typeof el.textContent == 'string')
return el.textContent;
if (typeof el.innerText == 'string')
return el.innerText;
return '';
}

var rows = t.rows;
var cells;
var t, jsonText = [];

for (var i=0, nrows=rows.length; i<nrows; i++){
cells = rows.cells;
t = [];

for (var j=0,ncells=cells.length; j<ncells; j++){
t.push(getText(cells[j]));
}

jsonText.push('[' + t.join(', ') + ']');
}

return '[' + jsonText.join(', ') + ']';
}
 
E

Elegie

RobG wrote:

Hi,
Sounds fairly trivial.
If by "content" you mean text content, loop
over the rows and create one array for each, stuff the contents of
each cell into a row array element and return it as a JSON formatted
text string, e.g.

Your code does convert the table content into arrays (which was the
first requirement, indeed trivial), but you seem to have stopped before
converting to the JSON format :)

<URL:http://www.json.org/>

AFAICS, a JSON entity can contain values such as string, number, object,
array, true, false, null. Since we would originally be parsing text, I
would say that objects and arrays should probably be left unexpanded,
however other values should probably be analyzed and JSON-formatted,
given their final status (valid value or text).

Values such as 'true', false' and 'null' are left "as is", numbers
should be trimmed and checked against a good regexp, and strings should
be surrounded by double quotes (taking care of escaping issues,
essential in serialization processes).


Regards,
Elegie.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top