Ho un oggetto python che include alcuni decimali. Ciò sta causando l'interruzione di json.dumps().La serializzazione da Python a JSON non riesce su Decimale
Ho ottenuto la seguente soluzione da SO (ad esempio Python JSON serialize a Decimal object) ma la soluzione di riepilogo ancora non funziona. Sito Web Python - ha la stessa risposta esatta.
Qualche suggerimento su come farlo funzionare?
Grazie. Di seguito è il mio codice. Sembra che i dump() non entrino nemmeno nell'encoder specializzato.
[email protected]:~/python> cat test1.py
import json, decimal
class DecimalEncoder(json.JSONEncoder):
def _iterencode(self, o, markers=None):
print "here we go o is a == ", type(o)
if isinstance(o, decimal.Decimal):
print "woohoo! got a decimal"
return (str(o) for o in [o])
return super(DecimalEncoder, self)._iterencode(o, markers)
z = json.dumps({'x': decimal.Decimal('5.5')}, cls=DecimalEncoder)
print z
[email protected]:~/python> python test1.py
Traceback (most recent call last):
File "test1.py", line 11, in <module>
z = json.dumps({'x': decimal.Decimal('5.5')}, cls=DecimalEncoder)
File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/encoder.py", line 201, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/encoder.py", line 264, in iterencode
return _iterencode(o, 0)
File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: Decimal('5.5') is not JSON serializable
[email protected]:~/python>
Sia la seconda risposta sulla pagina collegata e [la documentazione Python reale] (http: // docs.python.org/2/library/json.html#json.JSONEncoder) fornisce la risposta corretta, che è quella di sovrascrivere 'default'. Dovrebbe essere ovvio che non si dovrebbe sovrascrivere '_iterencode', poiché la sottolineatura principale implica che si tratta di un metodo solo interno. –
json non sa come gestire 'Decimal', quindi si dovrebbe estendere il codificatore JSON per le strutture dati Pythonhttp: //docs.python.org/2/library/json.html#py-to-json-table – oleg