Can't serialize select result with fields from two or more tables in JSON

26 views
Skip to first unread message

Rafael Sales

unread,
Apr 20, 2011, 6:09:23 PM4/20/11
to web2py-users, fran...@gmail.com
Hello,
I'm facing a very tricky error with JSON.
I have an action that must return a json object with the results of a
select. The select must return fields from two tables. When I use this
kind of select return fields from two or more tables, the simple json
cannot serialize the result of the select.
[Code A] Here's my code:
def getDespesasPorHospedagem():
id_locado = request.vars.id_locado
if id_locado == None:
return response.json({'despesas': []})

orderBy = db.despesa.id.lower()
query = ((db.despesa.id_locado == id_locado) &
(db.despesa.id_servico == db.servico.id))
despesas = db(query).select(db.despesa.ALL, db.servico.ALL,
orderby = orderBy)

return response.json({'despesas': despesas})

Invoking the URL (.../getDespesasPorHospedagem?id_locado=100) throws
the following error: http://pastebin.com/PsX8dD4e
Changing the return expressions respectively to: "return dict(despesas
= [])" and "return dict(despesas = despesas)", the URL above works
without any error and shows the result dictionary, but:
- the URL (.../getDespesasPorHospedagem.json?id_locado=100) returns
"no json" and
- the URL (.../getDespesasPorHospedagem.xml?id_locado=100) returns
the correct XML.

[Code B]
When I change my action as below, which have the same effect for me
although less concise, the return object can be serialized
successfully. And note that I'm using the same queries:
def getDespesasPorHospedagem():
id_locado = request.vars.id_locado
if id_locado == None:
return response.json({'despesas': [], 'servicos': []})

orderBy = db.despesa.id.lower()
query = ((db.despesa.id_locado == id_locado) &
(db.despesa.id_servico == db.servico.id))
despesas = db(query).select(db.despesa.ALL, orderby = orderBy)

orderBy = db.despesa.id.lower()
query = ((db.despesa.id_locado == id_locado) &
(db.despesa.id_servico == db.servico.id))
servicos = db(query).select(db.servico.ALL, orderby = orderBy)

return response.json({'despesas': despesas, 'servicos': servicos})

So... is this a bug?
Rafael Sales

Franzé Jr.

unread,
Apr 21, 2011, 12:31:20 PM4/21/11
to web2py-users
I think so

Rafael Sales

unread,
Apr 21, 2011, 1:11:36 PM4/21/11
to web2py-users
By the way, I'm using Ubuntu 10.10 and the current version of Web2Py:
1.94.6
Reply all
Reply to author
Forward
0 new messages