I was migrating some of the ReST APIs that I'd hand-rolled over to the 
new(?) ReST facilities in web2py and noticed while going through the 
examples (http://web2py.com/books/default/chapter/29/10#Restful-Web-Services) 
that JSON serialization kept failing. I'm using 1.99.7. 

It looks like the problem is all of the functions (lambda and methods) 
attached to each dal object passed to the view:

TRACEBACK

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

Traceback (most recent call last):
  File "/Users/prog/web2py/generic/gluon/restricted.py", line 205, in restricted
    exec ccode in environment
  File "/Users/prog/web2py/generic/applications/resttest/views/generic.json", 
line 2, in <module>
  File "/Users/prog/web2py/generic/gluon/serializers.py", line 61, in json
    return json_parser.dumps(value,default=default)
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py",
 line 238, in dumps
    **kw).encode(obj)
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py",
 line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py",
 line 264, in iterencode
    return _iterencode(o, 0)
  File "/Users/prog/web2py/generic/gluon/serializers.py", line 37, in 
custom_json
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <function <lambda> at 0x100e70500> is not JSON serializable

I first wrote a filter to weed out functions which was useful in getting 
the examples to work but was much more involved than required to solve my 
use case. In the end I went with a list comprehension containing only the 
fields that I needed. Instead of: 

  return dict(person = db.person(id))

I used something like:
  return dict([(field,db.person(id)[field]) for field in ['name', 'id', 
'info']])


Has anyone ever gotten the examples working without using such tricks? it 
took a while for me to get from 1.95.x up to 1.99.x so I don't know whether 
my experience is unique or due to a code change. 

Thanks. 


Reply via email to