3

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?

shx2
  • 57,957
  • 11
  • 121
  • 147
David Yang
  • 1,991
  • 8
  • 27
  • 42

1 Answers1

1

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.

Community
  • 1
  • 1
Thane Brimhall
  • 8,839
  • 5
  • 32
  • 49