flask icon indicating copy to clipboard operation
flask copied to clipboard

json_encoder not invoked from flask.jsonify

Open andybarilla opened this issue 11 years ago • 14 comments

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)

andybarilla avatar Apr 21 '15 14:04 andybarilla

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)

mreinhardt avatar Apr 22 '15 06:04 mreinhardt

I think this should be fixed together with/by https://github.com/mitsuhiko/flask/issues/248.

untitaker avatar Apr 22 '15 07:04 untitaker

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.

andybarilla avatar Apr 22 '15 19:04 andybarilla

Good point. I wasn't sure of your use case.

mreinhardt avatar Apr 22 '15 21:04 mreinhardt

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?

davidism avatar Apr 24 '15 16:04 davidism

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.

andybarilla avatar May 22 '15 19:05 andybarilla

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.

0xManyu avatar Jun 12 '15 06:06 0xManyu

@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.

justanr avatar Jun 12 '15 16:06 justanr

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 avatar Nov 03 '15 14:11 davidism

@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 avatar Nov 04 '15 18:11 untitaker

@untitaker oops, that got burried in the comments, I see what the issue is now.

davidism avatar Nov 04 '15 19:11 davidism

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?

jab avatar Nov 04 '15 20:11 jab

Running the app posted in the original issue now outputs

{
  "key": "a", 
  "value": "b"
}

Looks like you can safely close this issue.

wldtyp avatar Jun 02 '16 21:06 wldtyp

Excellent!

untitaker avatar Jun 03 '16 04:06 untitaker