SQLROWS output to JSON

7 views
Skip to first unread message

Timbo

unread,
Sep 19, 2008, 1:54:33 PM9/19/08
to web2py Web Framework
I use YUI for my web development. YUI can do lots of cool things with
your data if you feed it a JSON array of objects. I don't know about
other JS libraries, but I can say that accessing your data in JS in
this form is much faster and easier (with more readable code) than the
solution provided in this discussion:

http://groups.google.com/group/web2py/browse_thread/thread/cd6239716cf1d989/21e557c08f9113fd?lnk=gst&q=sqlrows+json#21e557c08f9113fd

I propose the following added method to the SQLRows object in order to
provide what I've described above:

---------------------
import gluon.contrib.simplejson as sj

...

def json(self, columnHeaders=True):
"""
serializes the table to a JSON list of objects
"""
cols=range(len(self.colnames))
colnames = self.colnames
resp = self.response
rows = range(len(self))
# Looping through a potentially large list, demands that we
precompute
# as much as we can to slim down the loop.
if columnHeaders:
lst=[dict([(colnames[j], resp[i][j]) for j in cols]) for i in
rows]
else:
lst=[[resp[i][j] for j in cols] for i in rows]
return sj.dumps(lst)

---------------------------
Note that setting the columnHeaders option to False will provide the
output as a list of lists per the discussion at:

http://groups.google.com/group/web2py/browse_thread/thread/cd6239716cf1d989/21e557c08f9113fd?lnk=gst&q=sqlrows+json#21e557c08f9113fd

I think this patch is Pythonic and web2pyic. Who's with me?

Massimo Di Pierro

unread,
Sep 19, 2008, 1:58:50 PM9/19/08
to web...@googlegroups.com
So far it has been kind of a policy not to call any function in the
contrib moduels from proper web2py modules. The reason is that the
stuff in contrib may change over time.
Nevertheless I agree that json is going away and actually simplejson
will be part of the standard libraries in python 3.0.

If no objections I will add this. I will try release 1.43 by Thursday
and I will include it.

Massimo

Reply all
Reply to author
Forward
0 new messages