I have the following application and test:
app.py
from json import JSONEncoder
from flask import Flask, jsonify
class CustomJSONEncoder(JSONEncoder):
def default(self, obj):
return {"hello": "world"}
app = Flask(__name__)
app.json_encoder = CustomJSONEncoder
@app.route('/')
def main():
return jsonify({'yep': 'this worked'})
if __name__ == '__main__':
app.run()
test_app.py
import json
from app import app
def test_this_should_work():
test_client = app.test_client()
rv = test_client.get('/')
assert json.loads(rv.data.decode()) == {'hello': 'world'}
As best as I can tell from this example, my code should work and return this other dictionary. However, it doesn't. You can run it via python app.py
or py.test
(if you install py.test), and you'll observe that both times return {"yep": "this worked"}
.
Something is wrong here - what am I missing?
This is not an issue with Flask, which does send the custom encoder. It's just the way Python's json library works. The default
function is only called if the object being dumped is not recognized. Since you're dumping a string, which is a type recognized by the library, it's just dumped as is.
If you want to transform your data, do the transformation before serializing it.
This recently came up on the Flask issue tracker as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With