Set Object Is Not Json Serializable
When I try to run the following code: import json d = {'testing': {1, 2, 3}} json_string = json.dumps(d) I get the following exception: Traceback (most recent call last): File
Solution 1:
Turn sets into lists before serializing, or use a custom default
handler to do so:
defset_default(obj):
ifisinstance(obj, set):
returnlist(obj)
raise TypeError
result = json.dumps(yourdata, default=set_default)
Solution 2:
You can't fix it.
This error means just "json.dumps doesn't support data type "set".You should know JSON comes from javascript. And there is no data type like Python's "set" in javascript. So Python can't treat 'set' using JSON.
So you need another approach like @Martijn Pieters mentioned.
UPDATE
I forgot to say this.
If you want to dump "set" or any other python object that is not supported JSON, you can use pickle
or cPickle
module. If you use the "dump.txt" only from Python, this may be helpful.
import cPickle
d = {'testing': {1, 2, 3}}
#dumpwithopen("pickledump.txt", "w") as fp:
cPickle.dump(d, fp)
#loadwithopen("pickledump.txt", "r") as fp:
x = cPickle.load(fp)
Post a Comment for "Set Object Is Not Json Serializable"