json_encoder not invoked from flask.jsonify
I created a custom JSON encoder class extended from flask.json.JSONEncoder but it is not called when calling flask.jsonify. Additionally, I removed my custom JSON encoder and confirmed that flask.json.JSONEncoder isn't called either via a break statement in Pycharm.
from flask import Flask
from flask import jsonify
from flask.json import JSONEncoder
class MyEncoder(JSONEncoder):
def default(self, obj):
if hasattr(obj, '__json__'):
return obj.__json__()
else:
try:
iterable = iter(obj)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, obj)
class MyClass(object):
key = 'a'
value = 'b'
def __json__(self):
return {'key': self.key, 'value': self.value}
app = Flask(__name__)
app.json_encoder = MyEncoder
@app.route('/')
def hello_world():
return jsonify(MyClass())
if __name__ == '__main__':
app.run(debug=True)
The reason you never see either the default or your custom json encoder execute is that the class instance MyClass() is not iterable. This line of jsonify runs dict(MyClass()) which results in a TypeError: 'MyClass' object is not iterable.
You could probably figure out a way to do what you want with a custom JSON encoder, but I don't think you need to. Instead you can make a base class that implements a custom iterator and have all of the classes that need to be jsonified inherit it as a mixin. Then the class instance can be passed to jsonify as *args like this:
from flask import Flask
from flask import jsonify
class JSONIterator(object):
def __iter__(self):
exclude_prefixes = ('__', '_{}__'.format(self.__class__.__name__))
return iter([[
(k, v) for k, v in self.__class__.__dict__.iteritems()
if not (k.startswith(exclude_prefixes) or hasattr(v, '__call__'))
]])
class MyClass(JSONIterator):
key = 'a'
value = 'b'
app = Flask(__name__)
@app.route('/')
def hello_world():
return jsonify(*MyClass())
if __name__ == '__main__':
app.run(debug=True)
I think this should be fixed together with/by https://github.com/mitsuhiko/flask/issues/248.
That would solve the issue with converting a single object to JSON but if you try and do an array of MyClasses a custom json encoder would be required again.
Good point. I wasn't sure of your use case.
Flask does use your custom encoder: https://github.com/mitsuhiko/flask/blob/0.10-maintenance/flask/json.py#L97.
class Custom(object):
pass
class CustomEncoder(flask.JSONEncoder):
def default(self, o):
if isinstance(o, Custom):
return 'cabbage'
return flask.JSONEncoder.default(self, o)
jsonify(values=[Custom(), Custom()]) # response is {'values': ['cabbage', 'cabbage']}
Note that Python's json library will only call default if it does not know how to serialize the object. For example, a str subclass will not go through default, it will be treated as a str. What is the actual custom object you are trying to dump?
The main reason for this is so I can have a custom JSON encoder which handle streaming of objects coming from a generator function. I don't want to load all the results into memory before returning them.
I think the problem of this is python do not support to transform any object to JSON.
May be we can implement a interface just like @mreinhardt said. to support jsonify any object but not only basic object to JSON.
@wswuai @mreinhardt The easiest way I've found to do this is with Marshmallow. It works out of the box with Flask but there's a compatibility layer for creating URLs. I'm not sure how it'd handle streaming requests though.
This is something that should be solved by a serialization library such as Marshmallow (there are plenty of others too). Flask is not in a position to change how basic JSON serialization works.
@davidism
This line of jsonify runs dict(MyClass()) which results in a TypeError: 'MyClass' object is not iterable.
This is what I wanted to fix for 1.0. It's almost a duplicate of #248, but I want to ensure custom classes like that work in jsonify after we fix that issue, which is why I left this one open.
@untitaker oops, that got burried in the comments, I see what the issue is now.
Hi @untitaker et al., I opened #1602 a few days ago and think it might fit in with this / the desired work on flask.json for 1.0. Would it be helpful if I worked up a PR?
Running the app posted in the original issue now outputs
{
"key": "a",
"value": "b"
}
Looks like you can safely close this issue.
Excellent!