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

bur*_*ing 2 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
Run Code Online (Sandbox Code Playgroud)

Ale*_*ich 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)
Run Code Online (Sandbox Code Playgroud)

更新

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

from django.core.serializers.json import DjangoJSONEncoder
json.dumps(chart_list,..., cls=DjangoJSONEncoder)
Run Code Online (Sandbox Code Playgroud)

  • 事实上,几乎所有代码都包含在django中作为`django.core.serializers.json.DjangoJSONEncoder`. (2认同)
  • 不幸的是,更新版本的行为与原始版本完全不同,因为DjangoJSONEncoder返回Decimals的字符串而不是浮点数 (2认同)