2

I have a dictionary with frozenset-typed (variable-length, non-duplicate data) keys and I need to write this dictionary into a JSON file.

However, my problem is that frozenset (although immutable) is not a Python simple data type and I get this type error in result of json.dump(myDict, myFile):

TypeError: key frozenset({'myKey'}) is not a string

Could anyone please help me with some hints or solutions? I'm using Python 3.4.

I know I can manually serialize the object, but aren't there any other more automatic ways?!

ZygD
  • 22,092
  • 39
  • 79
  • 102
  • 1
    "myKey" <- do double quotes. Python is assuming this is a character. But is probably something else as well – FirebladeDan Jul 28 '15 at 18:38
  • 2
    Python does not make that distinction; you're thinking of C. `'myKey'` and `"myKey"` produce the same string. – chepner Jul 28 '15 at 18:44
  • JSON keys have to be strings, so you have to convert your keys to strings, or change your data format – Ale Jul 28 '15 at 18:45
  • 1
    See this: http://stackoverflow.com/questions/8230315/python-sets-are-not-json-serializable – Ale Jul 28 '15 at 18:48
  • 1
    The `json` module doesn't seem to apply custom encoders to the keys of a dictionary when encoding the dictionary. The `dict` passed to `dump` must already have keys of a type known to `json`. – chepner Jul 28 '15 at 18:56
  • As Ale says, the keys have to be strings. I find the best way to do this is str(sorted(myset)) -- if you don't sort, you might get different data for the same set. – Patrick Maupin Jul 28 '15 at 19:06
  • You may find [_Making object JSON serializable with regular encoder_](http://stackoverflow.com/questions/18478287/making-object-json-serializable-with-regular-encoder) useful. – martineau Jul 28 '15 at 19:15
  • Thanks a lot everyone. I finally serialized the object before passing it to json.dump. – Gadfly4ever Jul 29 '15 at 15:37

0 Answers0