【问题标题】:Django how to pass Decimal objects to jsonDjango如何将十进制对象传递给json
【发布时间】:2012-10-26 18:04:04
【问题描述】:

我有一个包含十进制对象的查询集。我想将这些数据传递给 json 转储:

ql = Product.objects.values_list('length', 'width').get(id=product_id)
data = simplejson.dumps(ql)

TypeError: Decimal('62.20') is not JSON serializable

我应该如何将这些值传递给 json.当然,我可以将值转换为字符串 - 但我猜这不是一个好的解决方案。

非常感谢任何帮助。

【问题讨论】:

    标签: django json


    【解决方案1】:

    这是我在这个问题上找到的答案:Python JSON serialize a Decimal object

    子类化 json.JSONEncoder 怎么样?

    class DecimalEncoder(simplejson.JSONEncoder):
        def _iterencode(self, o, markers=None):
            if isinstance(o, decimal.Decimal):
                # wanted a simple yield str(o) in the next line,
                # but that would mean a yield on the line with super(...),
                # which wouldn't work (see my comment below), so...
                return (str(o) for o in [o])
            return super(DecimalEncoder, self)._iterencode(o, markers)
    

    在你的情况下,你会这样使用它:

    data = simplejson.dumps(ql, cls=DecimalEncoder)
    

    【讨论】:

      【解决方案2】:

      Django 已经包含一个可以处理小数和日期时间的编码器:django.core.serializers.json.DjangoJSONEncoder。只需将其作为cls 参数传递:

      data = simplejson.dumps(ql, cls=DjangoJSONEncoder)
      

      【讨论】:

      • 我这里有问题。我将上下文设置为 2 个小数点,但它不断转储整个 8 或 10 个小数点。我在这里缺少什么?
      • 请注意,如果您在使用.values.values_list 时序列化查询集,则会收到TypeError 错误,该查询集返回ValuesQuerySet - 强制进入列表以使其正常工作,因此使用上面例如:data = simplejson.dumps(list(ql), cls=DjangoJSONEncoder)
      猜你喜欢
      • 2012-04-12
      • 1970-01-01
      • 2011-09-05
      • 2017-01-11
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      相关资源
      最近更新 更多