Skip to content

Conversation

juannorris
Copy link

Fix for #873.

Use flask.json instead of json standard library as the default JSON encoder.

Overriding behavior remains, but this adds the ability for flask_restful to pick up the encoder defined for the app, or the api blueprint.

from flask_restful import Api
from flask import Blueprint
from flask import json

class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        return 'custom_flask_encoder'

blueprint = Blueprint('test', __name__)
blueprint.json_encoder = CustomJSONEncoder
api = flask_restful.Api(blueprint)
app = Flask(__name__)
app.register_blueprint(blueprint, url_prefix='/blueprint')

or

app = Flask(__name__)
app.json_encoder = CustomJSONEncoder
api = flask_restful.Api(app)

Fix for flask-restful#873.

Use `flask.json` instead of `json` standard library as the default JSON encoder.

Overriding behavior remains, but this adds the ability for `flask_restful` to pick up the encoder defined for the app, or the api blueprint.

```python
from flask_restful import Api
from flask import Blueprint
from flask import json

class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        return 'custom_flask_encoder'

blueprint = Blueprint('test', __name__)
blueprint.json_encoder = CustomJSONEncoder
api = flask_restful.Api(blueprint)
app = Flask(__name__)
app.register_blueprint(blueprint, url_prefix='/blueprint')
```

or

```python
app = Flask(__name__)
app.json_encoder = CustomJSONEncoder
api = flask_restful.Api(app)
```
@juannorris juannorris changed the title Use flask.json as default encoder Use flask.json as default encoder Mar 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant