渲染时捕获TypeError:十进制('51 .8')不是JSON可序列化的

时间:2011-12-28 06:11:52

标签: python django

我正在使用Python 2.6.5和Django 1.3。运行以下代码时我收到上述错误

if chart_list is not None:
    if isinstance(chart_list, (Chart, PivotChart)):
        chart_list = [chart_list]
    chart_list = [c.hcoptions for c in chart_list]
    render_to_list = [s.strip() for s in render_to.split(',')]
    for hco, render_to in izip_longest(chart_list, render_to_list):
        if render_to:
            hco['chart']['renderTo'] = render_to
    embed_script = (embed_script % (simplejson.dumps(chart_list,skipkeys=False,   ensure_ascii=True, 
  check_circular=True, allow_nan=True, cls=None),
                                    CHART_LOADER_URL))
else:
    embed_script = embed_script %((), CHART_LOADER_URL)
return mark_safe(embed_script

2 个答案:

答案 0 :(得分:8)

使用自定义JSONEncoder应该有帮助

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        super(DecimalEncoder, self).default(o)

# and then:
json.dumps(chart_list,..., cls=DecimalEncoder)

更新

根据丹尼尔的评论更新(更多DRY方式)

from django.core.serializers.json import DjangoJSONEncoder
json.dumps(chart_list,..., cls=DjangoJSONEncoder)

答案 1 :(得分:-1)

一个简单快捷的解决方案是,在传递给dumps方法

之前,将此十进制对象转换为字符串
decimal_value = Decimal('51.8')
simplejson.dumps(str(decimal_value))