diff --git a/CHANGES b/CHANGES index 5ea2baae..5df663ea 100644 --- a/CHANGES +++ b/CHANGES @@ -51,6 +51,9 @@ Version 1.0 loading. - Ported testsuite to py.test. - Deprecated ``request.json`` in favour of ``request.get_json()``. +- Add "pretty" and "compressed" separators definitions in jsonify() method. + Reduces JSON response size when JSONIFY_PRETTYPRINT_REGULAR=False by removing + unnecessary white space included by default after separators. Version 0.10.2 diff --git a/flask/json.py b/flask/json.py index a0ed7041..318fe28b 100644 --- a/flask/json.py +++ b/flask/json.py @@ -227,15 +227,22 @@ def jsonify(*args, **kwargs): This function's response will be pretty printed if it was not requested with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false. + Compressed (not pretty) formatting currently means no indents and no + spaces after separators. .. versionadded:: 0.2 """ + indent = None + separators = (',', ':') + if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \ and not request.is_xhr: indent = 2 + separators = (', ', ': ') + return current_app.response_class(dumps(dict(*args, **kwargs), - indent=indent), + indent=indent, separators=separators), mimetype='application/json') diff --git a/tests/test_basic.py b/tests/test_basic.py index 55fd155a..2f024a5d 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -959,6 +959,36 @@ def test_make_response_with_response_instance(): assert rv.headers['X-Foo'] == 'bar' +def test_jsonify_no_prettyprint(): + app = flask.Flask(__name__) + app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False}) + with app.test_request_context(): + compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}' + uncompressed_msg = { + "msg": { + "submsg": "W00t" + }, + "msg2": "foobar" + } + + rv = flask.make_response( + flask.jsonify(uncompressed_msg), 200) + assert rv.data == compressed_msg + + +def test_jsonify_prettyprint(): + app = flask.Flask(__name__) + app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True}) + with app.test_request_context(): + compressed_msg = {"msg":{"submsg":"W00t"},"msg2":"foobar"} + pretty_response =\ + b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}' + + rv = flask.make_response( + flask.jsonify(compressed_msg), 200) + assert rv.data == pretty_response + + def test_url_generation(): app = flask.Flask(__name__)