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
73.7k6 gold badges71 silver badges95 bronze badges
asked Mar 25, 2020 at 9:23
1

4 Answers 4

6

Another way is to use tolist numpy.org 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 Mar 25, 2020 at 9:32
Sign up to request clarification or add additional context in comments.

1 Comment

list() returns numbers wrapped in numpy types. That's creating the json problem. tolist unpacks them all the way.
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))
answered Mar 25, 2020 at 9:29

Comments

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.

answered Mar 25, 2020 at 9:29

1 Comment

X.tolist() is faster and easier.
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))
answered Mar 25, 2020 at 9:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.