How I can serialize the json in Python?

Jaffer Wilson :

Here is the code and the error follows:

import numpy as np
import json
X=np.arange(20)
t=dict(x=list(X))
print(json.dumps(t))

The error is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\json\__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python35\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python35\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Python35\lib\json\encoder.py", line 180, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: 0 is not JSON serializable

Please let me know what I can do to get rid of this. I am trying to pass this value to the plotting windows and the same error is occurring.

Amazing Things Around You :

Your json values are not properly type cast I guess. tried to find something related to your query: TypeError: Object of type 'int64' is not JSON serializable

You just need to type cast it:

>>> t = dict(x=list(float(j) for j in X))
>>> json.dumps(t)
'{"x": [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0]}'

I guess that will work.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360612&siteId=1