By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,251 Members | 2,656 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,251 IT Pros & Developers. It's quick & easy.

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

P: n/a
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

Jun 13 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On Jun 14, 9:19 am, "phil.swen...@gmail.com" <phil.swen...@gmail.com>
wrote:
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[i].cells;
t = [];

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

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

return '[' + jsonText.join(', ') + ']';
}
--
Rob
Jun 14 '07 #2

P: n/a
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.

Jun 14 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.