Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

support serializing arrays as top level object

  • Loading branch information...
commit d362bf9b77f4c3b8d908f3c4a00e0543274a0fdf 1 parent edb1d91
@corydolphin authored
Showing with 26 additions and 9 deletions.
  1. +11 −4 example.py
  2. +15 −5 flask_jsonpify.py
View
15 example.py
@@ -9,17 +9,24 @@
:license: MIT/X11, see LICENSE for more details.
"""
from flask import Flask
-from flask.ext.jsonpify import jsonify
+
+try:
+ import flask_jsonpify.jsonify
+except:
+ from flask.ext.jsonpify import jsonify
app = Flask(__name__)
SECRET_KEY = "yeah, not actually a secret"
app.config.from_object(__name__)
-@app.route("/")
-def index():
- return jsonify(user="lala")
+@app.route("/user/<user_id>")
+def show_user(user_id):
+ return jsonify(user={"name":"johnny droptables", "id":user_id})
+@app.route("/users")
+def list_users():
+ return jsonify([{"name":"johnny droptables-%i"%i, "id":i} for i in range(10)])
if __name__ == "__main__":
app.run(debug=True)
View
20 flask_jsonpify.py
@@ -10,13 +10,22 @@ def __pad(strdata):
else:
return strdata
+def __dumps(*args, **kwargs):
+ """ Serializes `args` and `kwargs` as JSON. Supports serializing an array
+ as the top-level object, if it is the only argument.
+ """
+ indent = None
+ if current_app.config.get('JSONIFY_PRETTYPRINT_REGULAR', False) \
+ and not request.is_xhr:
+ indent = 2
+ return json.dumps(args[0] if len(args) is 1 else dict(*args, **kwargs), indent=indent)
def jsonpify(*args, **kwargs):
"""Creates a :class:`~flask.Response` with the JSON or JSON-P representation of
the given arguments with an `application/json` mimetype. The arguments
- to this function are the same as to the :class:`dict` constructor. If a
- `callback` is specified in the request arguments, the response is
- JSON-Padded.
+ to this function are the same as to the :class:`dict` constructor, but also
+ accept an array. If a `callback` is specified in the request arguments, the
+ response is JSON-Padded.
Example usage::
@@ -54,8 +63,9 @@ def get_current_user():
.. versionadded:: 0.2
"""
- return current_app.response_class(__pad(json.dumps(dict(*args, **kwargs),
- indent=None if request.is_xhr else 2)),
+
+ return current_app.response_class(__pad(__dumps(*args, **kwargs)),
mimetype='application/json')
+
jsonify = jsonpify # allow override of Flask's jsonify.
Please sign in to comment.
Something went wrong with that request. Please try again.