The json
library, encoder
module, raises a TypeError
exception, which I think should not be raised. Hence I think the Series.tolist()
method may be at fault here and not json
standard library.
import pandas as pd
import json
s = pd.Series([1, 2, 3])
json.dumps(s.tolist())
Gives:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/json/__init__.py", line 230, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python3.4/json/encoder.py", line 192, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.4/json/encoder.py", line 173, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: 1 is not JSON serializable
But
import pandas as pd
import json
s = pd.Series([1, 2, 3])
json.dumps(s.values.tolist())
Works:
'[1, 2, 3]'
I am aware of Series.to_json()
method, but I need to insert the values first into a nested dictionary which is only later serialized to JSON. That is how I came across this behaviour.
Output of pd.show_versions()
INSTALLED VERSIONS
------------------
commit: None
python: 3.4.4.final.0
python-bits: 64
OS: Linux
OS-release: 3.2.0-4-amd64
machine: x86_64
processor:
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
pandas: 0.18.0
nose: None
pip: 8.1.2
setuptools: 20.6.7
Cython: 0.24
numpy: 1.11.0
scipy: 0.18.0
statsmodels: None
xarray: None
IPython: None
sphinx: None
patsy: None
dateutil: 2.5.3
pytz: 2015.7
blosc: None
bottleneck: None
tables: None
numexpr: None
matplotlib: 1.5.1
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: 4.5.1
html5lib: 0.999
httplib2: 0.9.2
apiclient: None
sqlalchemy: None
pymysql: None
psycopg2: 2.6.1 (dt dec pq3 ext lo64)
jinja2: None
boto: None
Comment From: TomAugspurger
Can you try on the latest version of pandas? Your code works for me, and I think it was fixed by https://github.com/pandas-dev/pandas/pull/13050
Comment From: jreback
In [15]: import pandas as pd
...: import json
...: s = pd.Series([1, 2, 3])
...: json.dumps(s.tolist())
...:
Out[15]: '[1, 2, 3]'
In [16]: pd.__version__
Out[16]: '0.19.0'
Comment From: Dmitrii-I
I have upgraded pandas from 0.18.1 to 0.19.0, and now it indeed works. Thank you!