Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

keywords must be strings #11

Closed
emmanuelito opened this issue Apr 12, 2023 · 4 comments
Closed

keywords must be strings #11

emmanuelito opened this issue Apr 12, 2023 · 4 comments

Comments

@emmanuelito
Copy link

Python's JSON encoder allow integer as keys (and convert them as strings), but not flask-json.

>>> d = { 1 : "A" }
>>> json.dumps(d)
'{"1": "A"}'

>>> jsonify(d)
<Response 15 bytes [200 OK]>

>>> json_response(data_=d)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/opt/scodoc/venv/lib/python3.9/site-packages/flask_json.py", line 145, in json_response
    response = jsonify(data_) if data_ is not None else jsonify(**kwargs)
TypeError: keywords must be strings

This is a problem when one wants to replace Flask's default JSON encoder by FlaskJSON.

@skozlovf
Copy link
Owner

@emmanuelito Sorry for the long response.
This happens because json_response() passes data_ as keyword arguments to the flask.jsonify().
But you don't need to use json_response() if you want to use FlaskJSON encoder - it's auto used by the flask.jsonify() if you initialized FlaskJSON. So this should work:

from flask import Flask
from flask import jsonify

app = Flask('xxx')
flask_json.FlaskJSON(app)
app.config['JSON_USE_ENCODE_METHODS'] = True

class MyJsonItem(object):
    def __json__(self):
        return '<__json__>'
    def for_json(self):
        return '<for_json>'

with app.test_request_context('/fake'):
    r = jsonify(MyJsonItem())
assert r.json == '<__json__>'

@emmanuelito
Copy link
Author

@skozlovf thank you ! I understand now the source of the problem.
I was in fact using @as_json.
The point is that flask-json is not a drop-in replacement for regular Flask's jsonify, which can be annoying (maybe this detail should be stated in the doc?).

@skozlovf
Copy link
Owner

@emmanuelito

maybe this detail should be stated in the doc?

I'll think about it. I planned to update internals to follow new Flask 2.3 API and will improve stuff to handle this case. Let's keep the issue open.
Thanks.

skozlovf added a commit that referenced this issue May 6, 2023
Highlights:

* Allow both data_ and kwargs.
* Add numeric keys support (see #11).
skozlovf added a commit that referenced this issue May 6, 2023
See also #11.
@skozlovf
Copy link
Owner

skozlovf commented May 6, 2023

Fixed/improved in 0.4.0.

@skozlovf skozlovf closed this as completed May 6, 2023
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

No branches or pull requests

2 participants