create json using python flask

How to Create JSON Using Python Flask

This post is in reply to a user comment on the Working with JSON data in Python Flask post where one of the readers asked how to create JSON using Python. Given below is the sample json which we’ll try to create using Python.


{
    "Employees": [{
        "firstName": "Roy",
        "lastName": "Augustine"
    }, {
        "firstName": "Roy",
        "lastName": "Augustine"
    }]
}

Start by creating a simple python flask app with a method to return employee JSON data.


@app.route("/getEmployeeList")
def getEmployeeList():
    
    try:

       # Code will be here

    except Exception ,e:
        print str(e)

    return "Employee"

I’ll be importing json and jsonify library in the python app.


from flask import Flask,jsonify,json

Create JSON Using Python

The basic logic for creating the above JSON data is creating a dictionary and appending it to a list. Once the list is complete we’ll convert the list to JSON data. Here is the complete getEmployeeList python method :

@app.route("/getEmployeeList")
def getEmployeeList():
    
    try:

        # Initialize a employee list
        employeeList = []

        # create a instances for filling up employee list
        for i in range(0,2):
        empDict = {
        'firstName': 'Roy',
        'lastName': 'Augustine'}
            employeeList.append(empDict)
    
        # convert to json data
        jsonStr = json.dumps(employeeList)

    except Exception ,e:
        print str(e)

    return jsonify(Employees=jsonStr)

In the above code we have simply looped the data twice and created a dictionary empDict. Using json.dumps we converted the dictionary to json string. Finally, we used the jsonify library to create the required json data.

Save the changes and try to run the above code. http://localhost:5000/getEmployeeList should return the required JSON data:


{
    "Employees": [{
        "firstName": "Roy",
        "lastName": "Augustine"
    }, {
        "firstName": "Roy",
        "lastName": "Augustine"
    }]
}

Wrapping It Up

In this short tutorial, we saw how to create json using Python Flask. I would also recommend reading working with JSON data in Python Flask.

Also read : Other Python Programming Tutorials on CodeHandbook.

2 thoughts on “How to Create JSON Using Python Flask

  1. Hi,

    I tried the approach mentioned by you in this post.
    But, the problem is that it works only for a list defined in the code, like you did.

    It does not work for a list returned from MySQL DB with SQL Alchemy.

    Here is the code which I am trying:

    empList = Employees.query.filter_by(user_id=current_user_id)

    jsonStr = json.dumps(empList)

    strToReturn = jsonify(Employees=jsonStr)
    return strToReturn

    And here is the error stack:

    Traceback (most recent call last):
    File “X:dhprojproj_venvlibsite-packagesflaskapp.py”, line 2000, in __call__
    return self.wsgi_app(environ, start_response)
    File “X:dhprojproj_venvlibsite-packagesflaskapp.py”, line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
    File “C:Python27Libsite-packagesflask_restful__init__.py”, line 271, in error_router
    return original_handler(e)
    File “C:Python27Libsite-packagesflask_corsextension.py”, line 188, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
    File “X:dhprojproj_venvlibsite-packagesflaskapp.py”, line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
    File “C:Python27Libsite-packagesflask_restful__init__.py”, line 268, in error_router
    return self.handle_error(e)
    File “X:dhprojproj_venvlibsite-packagesflaskapp.py”, line 1988, in wsgi_app
    response = self.full_dispatch_request()
    File “X:dhprojproj_venvlibsite-packagesflaskapp.py”, line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
    File “C:Python27Libsite-packagesflask_restful__init__.py”, line 271, in error_router
    return original_handler(e)
    File “C:Python27Libsite-packagesflask_corsextension.py”, line 188, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
    File “X:dhprojproj_venvlibsite-packagesflaskapp.py”, line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
    File “C:Python27Libsite-packagesflask_restful__init__.py”, line 268, in error_router
    return self.handle_error(e)
    File “X:dhprojproj_venvlibsite-packagesflaskapp.py”, line 1639, in full_dispatch_request
    rv = self.dispatch_request()
    File “X:dhprojproj_venvlibsite-packagesflaskapp.py”, line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
    File “C:Python27Libsite-packagesflask_restful__init__.py”, line 477, in wrapper
    resp = resource(*args, **kwargs)
    File “X:dhprojproj_venvlibsite-packagesflaskviews.py”, line 84, in view
    return self.dispatch_request(*args, **kwargs)
    File “C:Python27Libsite-packagesflask_restful__init__.py”, line 587, in dispatch_request
    resp = meth(*args, **kwargs)
    File “C:Python27Libsite-packagesflask_jwt__init__.py”, line 177, in decorator
    return fn(*args, **kwargs)
    File “X:dhprojcode-baseprojappapihandler.py”, line 15, in get
    return get_emp_for_current_user()
    File “X:dhprojcode-baseprojappapifunctions.py”, line 16, in get_emp_for_current_user
    jsonStr = json.dumps(empList)
    File “X:dhprojproj_venvlibsite-packagesflaskjson.py”, line 126, in dumps
    rv = _json.dumps(obj, **kwargs)
    File “C:Python27Libjson__init__.py”, line 238, in dumps
    **kw).encode(obj)
    File “C:Python27Libjsonencoder.py”, line 203, in encode
    chunks = list(chunks)
    File “C:Python27Libjsonencoder.py”, line 436, in _iterencode
    o = _default(o)
    File “X:dhprojproj_venvlibsite-packagesflaskjson.py”, line 83, in default
    return _json.JSONEncoder.default(self, o)
    File “C:Python27Libjsonencoder.py”, line 178, in default
    raise TypeError(repr(o) + ” is not JSON serializable”)
    TypeError: is not JSON serializable

    Please help.

    Regards,
    ap ap

    1. I’m passing in the list of dictionary created by iterating the employee object. Hope u see the difference. What you need to do is instead of passing in the empList directly to Json.dumps create a dict list by iterating empList and pass it to Json.dumps. Hope I’m clear. Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *