3

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.

user2390182
  • 72,016
  • 6
  • 67
  • 89
Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139
  • For a more generic approach to serializing `numpy` data, check https://stackoverflow.com/questions/27909658/json-encoder-and-decoder-for-complex-numpy-arrays – user2390182 Mar 25 '20 at 09:42

4 Answers4

6

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]}
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
  • 1
    `list()` returns numbers wrapped in numpy types. That's creating the json problem. `tolist` unpacks them all the way. – hpaulj Mar 25 '20 at 15:00
3

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))
dzakyputra
  • 682
  • 4
  • 16
2

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))
Rakesh
  • 81,458
  • 17
  • 76
  • 113
2

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.