Skip to content

Instantly share code, notes, and snippets.

@ianfoo
Created March 28, 2023 22:17
Show Gist options
  • Save ianfoo/e67f55fce48e5975caadb09726368390 to your computer and use it in GitHub Desktop.
Save ianfoo/e67f55fce48e5975caadb09726368390 to your computer and use it in GitHub Desktop.
Python's stdlib json.dumps and Flask's jsonify render JSON slightly differently
import json
import flask
from hamcrest import assert_that, is_
"""
json.dumps, by default, will include a bit of whitespace, using default
separators (', ', ': ') for item_separator and key_separator, respectively.
Flask defaults to a slightly more compact representation, using (',', ':')
as its separators. Depending on your tests, this could come up, and you
might wonder why rendering to JSON sometimes appears with spaces and
sometimes doesn't. This might be why.
"""
dict_ = {'everything': 42, 'blarney': 'stone'}
list_ = [1, 2, "buckle", "my", "shoe"]
def test_json_dumps():
json_dict = json.dumps(dict_, sort_keys=True)
json_list = json.dumps(list_)
assert_that(json_dict, is_('{"blarney": "stone", "everything": 42}'))
assert_that(json_list, is_('[1, 2, "buckle", "my", "shoe"]'))
def test_flask_jsonify():
flask_app = flask.Flask(__name__)
with flask_app.app_context():
flask_json_dict = flask.jsonify(dict_)
flask_json_list = flask.jsonify(list_)
assert_that(
flask_json_dict.get_data(as_text=True).strip(),
is_('{"blarney":"stone","everything":42}')
)
assert_that(
flask_json_list.get_data(as_text=True).strip(),
is_('[1,2,"buckle","my","shoe"]')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment