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.