Reputation: 8666
I'm implementing my own JSONEncoder for handling different classes exactly as I need them. Unfortunately, my custom encoder returns somewhat malformed strings. They are surrounded by quotes and certain characters (quotes) are escaped.
Please use the following code to reproduce the behaviour:
import json
class CustomEncoder(json.JSONEncoder):
def default(self, givenObject):
#for testing purposes this always returns the same string
str = '{"id":0,"name":"Peter"}'
return str;
class AnyClass(object):
pass
encoder = CustomEncoder()
dummyClass = AnyClass()
#expected output: {"id":0,"name":"Peter"}
print encoder.encode(dummyClass)
#output: "{\"id\":0,\"name\":\"Peter\"}"
I'm using Python 2.7.
How can I prevent this behaviour? What do I do wrong?
Upvotes: 1
Views: 226
Reputation: 215039
default
should return an object, not a chunk of json:
import json
class CustomEncoder(json.JSONEncoder):
def default(self, givenObject):
obj = {"id":0,"name":"Peter"}
return obj
class AnyClass(object):
pass
encoder = CustomEncoder()
dummyClass = AnyClass()
print encoder.encode(dummyClass) # {"id": 0, "name": "Peter"}
http://docs.python.org/library/json.html#json.JSONEncoder.default:
Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).
Upvotes: 3
Reputation: 120576
Instead of
str = '{"id":0,"name":"Peter"}'
return str;
try returning an object instead
return {"id":0,"name":"Peter"}
As written, the library gets a string and encodes that to JSON by quoting it and escaping special characters.
Upvotes: 1