List As An Entry In A Dict Not Json Serializable
I need to save a list (or a numpy array) as one of the entries in a JSON file. I am getting the “not JSON-serializable” error, and I can’t figure out how to fix it (and also
Solution 1:
It looks like there is a bug in numpy
caused by a lack of flexibility in Python's json
module. There is a decent workaround in that bug report:
>>>import numpy, json>>>defdefault(o):...ifisinstance(o, numpy.integer): returnint(o)...raise TypeError...>>>json.dumps({'value': numpy.int64(42)}, default=default)
'{"value": 42}'
Essentially, json.dumps()
takes a default
argument:
default(obj) is a function that should return a serializable version of obj or raise
TypeError
. The default simply raisesTypeError
.
The workaround posted just passed a function to json.dumps()
that converts numpy.integer
values to int
.
Post a Comment for "List As An Entry In A Dict Not Json Serializable"