Re: How to convert a table to JSON (or to Javascript array)

Dave Crane
2007-06-14T08:48:11Z

Hi Phil,

There''s bound to be a way :-)

I''m not sure what you''re trying to do. Is it:
a) convert a table that''s already part of the page
b) retrieve some HTML from the server that describes a table, and convert that

Either way, you''ll need to traverse the DOM nodes and build up a
JavaScript
object as you go along, and then convert it to JSON afterwards (use
Object.toJSON() if you''ve got proto v1.5.1 -
http://prototypejs.org/api/object/tojson). (I presume you want to convert it
into a JSON string, rather than just into a JS object.)

Prototype doesn''t provide a great deal of help for the traversing the
DOM bit,
as they wisely tend to avoid working with XML docs and the DOM. So, your
choices are either to use standard DOM methods and properties such as
childNodes and getElementsByTagName() - the latter is easier to work with as
it is whitespace-independent - or use XPath. There''s a nice little
library
called mozXPath.js that gives you a consistent XPath API across Mozilla and
IE, but if you want to support Safari et al., best stick with the DOM.

Prototype''s Element methods - http://prototypejs.org/api/element - like
up()
and down() might help a bit along the way, but I think that''s about it.

If you''re retrieving the HTML fragment from the server, you might like
to
consider whether there''s a way of sending the JSON from the server
instead.

HTH

Dave

On Thursday 14 June 2007 01:57, phil swenson wrote:
> Is there a way to retrieve an HTML table in javascript and convert it
> to JSON using prototype?
>
> I''m stumped :(
>
> phil
>
>
> >
>
> --
> This email has been verified as Virus free
> Virus Protection and more available at http://www.plus.net

--
Author: Prototype & Scriptaculous in Action, Ajax in Practice, Ajax in
Action