2012-11-06 26 views
8

我有一個包含Decimal對象的查詢集。我想將這些數據傳遞給json dump:Django如何將小數對象傳遞給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。當然,我可以將這些值轉換爲字符串 - 但我猜這不是一個好的解決方案。

任何幫助非常感謝。

回答

20

Django的已經包括編碼器比可以處理小數,以及日期時間:django.core.serializers.json.DjangoJSONEncoder。只要通過cls參數即可:

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

很酷。這就是訣竅。 –

+0

我在這裏遇到問題。我將上下文設置爲2個小數點,但它始終傾倒整個8或10個小數點。我在這裏錯過了什麼? – Cheluis

+2

請注意,如果您在使用'.values'或'.values_list'返回一個'ValuesQuerySet' - 強制到列表中以使其工作時序列化查詢集時會出現'TypeError'錯誤,因此使用上述示例作爲示例:'data = simplejson.dumps(list(ql),cls = DjangoJSONEncoder)' –

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) 
+0

我仍然得到與此方法相同的錯誤。 –