How I can serialize the json in Python?

Question:

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:Python35libjson__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "C:Python35libjsonencoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:Python35libjsonencoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:Python35libjsonencoder.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.

Asked By: Jaffer Wilson

||

Answers:

One approach mapping int on array

Ex:

import numpy as np
import json
X=np.arange(20)
t=dict(x=list(map(int, X)))
print(json.dumps(t))
Answered By: Rakesh

I think that’s because json doesn’t recognize the numpy data type.

I tried this code and it worked.

import json
t= {'x': [i for i in range(20)]}
print(json.dumps(t))
Answered By: dzakyputra

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.

Another way is to use tolist method. This will

return a copy of the array data as a (nested) Python list. For a 1D
array, a.tolist() is almost the same as list(a).However, for a 2D
array, tolist applies recursively

>>> import numpy as np
>>> import json

>>> X = np.arange(20)
>>> t = dict(x=X.tolist())
>>> print(json.dumps(t))
{"x": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]}
Answered By: Abdul Niyas P M