Working with JSON in Python Flask


With the advent of JavaScript based web technologies and frameworks like AngularJS, Node.js etc., knowing how work with JSON is a must. In this tutorial, we’ll see how to use JSON in Python Flask web application. JSON is a lightweight data format which is widely used across web applications for interchanging data across and within web applications. JSON means JavaScript Object Notation. From the official docs,

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

An example of a JSON object is :

var jsonObject = [{

        "FirstName": "Code",
        "Lastname": "Handbook"
    }, {
        "FirstName": "Ravi",
        "Lastname": "Shanker"
    }, {
        "FirstName": "Salman",
        "Lastname": "Khan"
    }, {
        "FirstName": "Ali",
        "Lastname": "Zafar"
    }

];

What we’ll learn in this tutorial

In this tutorial, we’ll see how to work with JSON in Python. For the sake of simplicity, we’ll be using Flask framework for creating a simple web application and see how to interchange JSON in Python from server side to client side. This tutorial assumes the user to have the basic knowledge of Python programming language and Flask framework.

Getting Started

Once you have Flask and Python installed in your system, create a file called app.py and paste the following code:

from flask import Flask
app = Flask(__name__)

@app.route("/getEmployeeList")
def getEmployeeList():
    return "Return Employee JSON data"

if __name__ == "__main__":
    app.run()

Try running the app.py file and you should be able to view the application running at http://localhost:5000/getData.

python app.py

Return JSON in Python

Generally in an application it’s easier to manipulate data fetched from database if it’s kept as objects. And whenever we need to transfer the data to client side, we simply convert the data to JSON and send it to the client side. What we’ll try to do here is create a class , say for example, a class for employee. Then we’ll try to create a list of employee class object and convert it into JSON and transfer it to the client side.

Let’s start by creating an employee class in employee.py file :

class Employee:
    def __init__(self,firstName,lastName):
        self.firstName = firstName
    self.lastName = lastName

Import the employee.py file in the app.py, so that we can create an employee object.

from employee import Employee

Inside the getEmployeeList method in app.py, create 5 instances of the employee class.

# Initialize a employee list
employeeList = []

# create a instances for filling up employee list
for i in range(0,5):
    employee = Employee('first name','last name')
    employeeList.append(employee)

As seen in the above code, we have created 5 instances of the employee class and inserted it into employeeList. Just to make it a bit more realistic, let’s replace the hard coded first name and last name with random names. Install package names for random name generator.

pip install names

Import the above names package in the app.py file.

import names

Replace the hard coded first name and last as shown:

# create a instances for filling up employee list
for i in range(0,5):
    employee = Employee(names.get_first_name(),names.get_last_name())
    employeeList.append(employee)

Define a method called toJSON in the employee.py which would return the JSON for an employee instance.

def toJSON(self):
    return {"Employees": {'firstName': self.firstName,
                 'lastName': self.lastName}}

Next we’ll iterate the employee list object in the app.py and convert each employee object to JSON and then dump the data using json.dumps. Import JSON in the app.py file and then add the following code to convert employeeList object to JSON data.

jsonStr = json.dumps([e.toJSON() for e in employeeList])

Here is the full code from the app.py file:

from flask import Flask,json
from employee import Employee
import names

app = Flask(__name__)

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

        # Initialize a employee list
        employeeList = []

        # create a instances for filling up employee list
        for i in range(0,5):
            employee = Employee(names.get_first_name(),names.get_last_name())
            employeeList.append(employee)
    
    # convert to json data
        jsonStr = json.dumps([e.toJSON() for e in employeeList])

    except:
        print "error ", sys.exc_info()[0]

    return jsonStr

if __name__ == "__main__":
    app.run()

Try restarting the server and point your browser URL to http://localhost:5000/getEmployeeList and you should be able to view the JSON data in the web browser.

Convert Cursor Result Set to JSON

In the above section we saw how to convert a class instance or object list to JSON data. Now we’ll see how to convert a cursor result set to JSON data.

Assume that we are using the below code to fetch data from database :

resultSet = cursor.fetchall()

resultSet would be a list of items fetched from database. What we’ll do is iterate over the resultSet list and convert each item into a python dictionary with custom key.

empList = []
for emp in resultSet:
    empDict = {
        'Id': emp[0],
        'Name': emp[1],
        'Location': emp[2],
        'Address': emp[3]}
    empList.append(empDict)
return json.dumps(empList)

Wrapping It Up

In this tutorial, we saw how to work with JSON in python when writing web applications. Here I have dealt with two general cases where we need to convert the python class objects and result sets retrieved from database to JSON data. Have you worked with JSON data in python and if so, have you encountered any programming issues converting to JSON?

Do let us know you thoughts, suggestions and any corrections in the comments below.

Do have a look at other Python programming tutorials on CodeHandbook.