resp = web.Response(body=json.dumps(r, cls=CJsonEncoder, ensure_ascii=False, default=lambda o: o.__dict__).encode('utf-8'))
when I used jinja2, and retrieve date form MYSQL, but the error shown. data:
2015-09-01 2015-09-04
how to fix it? may i need convert jinja2 to django??
This has nothing to do with Django or Jinja2 or your Web framework. Your data contains date objects, and JSON has no date type, so the json module doesn't know how to store them. It tries to fall back to your default function, which just dumps all of an object's attributes, but the date type is implemented in C and doesn't have a Python dict of attributes.
You can fix this by expanding upon your default:
import datetime
def json_default(value):
if isinstance(value, datetime.date):
return dict(year=value.year, month=value.month, day=value.day)
else:
return value.__dict__
resp = web.Response(body=json.dumps(r, cls=CJsonEncoder, ensure_ascii=False, default=json_default).encode('utf-8'))
I recommend against using .__dict__ as a catch-all fallback, though — your output might contain private junk, and your JSON may not produce anything like your original data when decoded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With