Andy
Andy

Reputation: 950

TypeError with `int` for `jsonify` from Flask

When I jsonify a dictionary result that looks like

{'options': {'seriesName': 'Count', 'startYear': 2009, 'title': 'Title', 'startMonth': 9, 'startDay': 1, 'data': [39, 199, 1137, 1156, 1168, 1821, 1936, 214, 236, 260, 282, 305, 323, 344, 3565, 384, 411, 430, 4540, 473, 521, 548, 576, 6222, 6257, 6982, 7216, 2746, 78230, 8126, 85432, 943217, 1024323, 1113, 1155, 142196, 1243, 1271, 1290, 1327, 1365, 1407, 1451, 1537, 1642, 1742, 1811, 1862, 1936, 1978, 2012, 20655, 2093, 2156, 2203, 22289, 24319, 254424, 2614, 2682, 2755, 2811, 2862, 2949, 30262, 31615, 32301, 343309, 343299, 364236, 332721], 'yAxisLabel': 'Count', 'yMinValue': 0}}

I end up with

raise TypeError(repr(o) + " is not JSON serializable")
TypeError: 39 is not JSON serializable

To my understanding 39 should be serializable correct?

This appears to be failing on the first int in the list. Is there a behavior of jsonify that I am no aware of?

Upvotes: 1

Views: 1956

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124558

You don't have an actual integer. You probably have a numpy.float64 or similar object, which looks a lot like an integer when printed. Pandas dataframes produce these, for example, see their Gotchas documentation.

You'll have to convert these to int or teach the Flask JSONEncoder how to handle these, explicitly.

For a numpy ndarray convert to a list using the .tolist() method to get native Python types.

Upvotes: 5

Related Questions