David Yang
David Yang

Reputation: 2141

Python: Interesting json.dumps serialization quirk

I have a fairly complicated dictionary that I want to convert into a JSON object.

dataj = json.dumps(post_data)

I get the following error:

TypeError: 6 is not JSON serializable

However, if I print my dictionary:

print post_data

And I copy/paste this post_data back into the same variable:

post_data = pasted data

Json.dumps works. No idea why this is happening but I suspect it has something to do with proper line breaks when copying the text and pasting it back in. Any way I can avoid having to do this?

Upvotes: 3

Views: 144

Answers (1)

Thane Brimhall
Thane Brimhall

Reputation: 9555

Looks like you're using NumPy; I've run into this problem before.

NumPy represents non-serializable primitive-like data types as primitives when printing them. When you copy and paste the output, you're taking that text and re-entering it as an actual primitive (which is JSON serializable, of course).

So you basically have 2 options: refactor the code to use NumPy's .tolist() (and related functions) or enhance the JSON serializer to accept NumPy datatypes.

Upvotes: 1

Related Questions