[ckan-dev] Json serializer in Jinja2 Template

Qifeng.Bai at csiro.au Qifeng.Bai at csiro.au
Tue Jun 3 04:07:28 UTC 2014


Hi, there

I have a complex customized 'data object'  needed to be passed to the template. I implemented IPackageController and create that instance and added it into data_dict in 'after_show' method.

Here is the code, it works well, the template get the data and render it. However, when I tried to update the data, it reported me an error:
ckanext.nlmp.foiImpl.FoI instance at 0x7f810cfff4d0> is not JSON serializable

def after_show(self,context,data_dict):
       fois=[]
        impl = foiImpl.FoI()
        fois = impl.parse(data_dict['extras'])
        data_dict['FOI'] = fois
#         data_dict['FOI'] =json.dumps(fois,cls=FoIEncoder);

The error happened in:

Module ckan.lib.search.index:110 in index_package     [http://127.0.0.1:5000/_debug/media/plus.jpg]     <http://127.0.0.1:5000/dataset/edit/exp1>  view<http://127.0.0.1:5000/dataset/edit/exp1>
>>  <http://127.0.0.1:5000/dataset/edit/exp1> pkg_dict['data_dict'] = json.dumps(pkg_dict)
Module json:231 in dumps     [http://127.0.0.1:5000/_debug/media/plus.jpg]     <http://127.0.0.1:5000/dataset/edit/exp1>  view<http://127.0.0.1:5000/dataset/edit/exp1>
>>  <http://127.0.0.1:5000/dataset/edit/exp1> return _default_encoder.encode(obj)


I tried to run json.dumps(fois) and it failed. However, I can use json.dumps(fois,cls=FoIEncoder) by simply define an customized encoder:
class FoIEncoder(json.JSONEncoder):
    def default(self,obj):
        return obj.__dict__

When I used   data_dict['FOI'] =json.dumps(fois,cls=FoIEncoder), the template will get json-like string, but Jinja2 template does not offer a json filter.  Can you point me a solution to figure out this?

I think there are two ways, one way is to make my object json seriable,  the other is to register a json filter to Jinja2.  Each way is fine to me

Many thanks for your help

Cheers
Qifeng






[cid:image001.gif at 01CC55BF.85E7FEB0]

Qifeng Bai
Software Engineer
CSIRO Land and Water
Black Mountain, Canberra

Ph: +61-2-62465704
Web: www.clw.csiro.au



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.okfn.org/pipermail/ckan-dev/attachments/20140603/a38e4323/attachment-0002.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: image001.gif
Type: image/gif
Size: 2094 bytes
Desc: image001.gif
URL: <http://lists.okfn.org/pipermail/ckan-dev/attachments/20140603/a38e4323/attachment-0002.gif>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: image002.jpg
Type: image/jpeg
Size: 361 bytes
Desc: image002.jpg
URL: <http://lists.okfn.org/pipermail/ckan-dev/attachments/20140603/a38e4323/attachment-0002.jpg>


More information about the ckan-dev mailing list