Convert test client data to JSON


I'm building an app and I want to make some tests. I need to convert the response data from the test client to JSON.

The app:

tasks = [
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False

app = Flask(__name__, static_url_path="")

@app.route('/myapp/api/v1.0/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': [task for task in tasks]})

if __name__ == '__main__':

The tests:

class MyTestCase(unittest.TestCase):
    def setUp(self):['TESTING'] = True =

    def test_empty_url(self):
        response ='/myapp/api/v1.0/tasks')
        resp = json.loads(

if __name__ == '__main__':

When I try to convert to JSON, I get the following error:

TypeError: the JSON object must be str, not 'bytes'

How can I fix this error and get the JSON data?

3/5/2015 4:43:30 PM

Flask 1.0 adds the get_json method to the response object, similar to the request object. It handles parsing the response data as JSON, or raises an error if it can't.

data = response.get_json()

Prior to that, and prior to Python 3.6, json.loads expects text, but data is bytes. The response object provides the method get_data, with the as_text parameter to control this.

data = json.loads(response.get_data(as_text=True))
3/22/2019 5:17:08 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow