How to convert MySQL query result to JSON in Python

Theory of Computation
In this article, you will learn a simple process to convert MySQL query result to JSON using Python programming.
JSON (JavaScript Object Notation) is a lightweight, open standard file format. It is an array data type and consisting of attribute-value pairs. It is easy to read and write for humans. It is used primarily to transmit data between a web application and a server. JSON is popular among developers for data serialization. It is so popular that every modern programming language has methods to generate and parse JSON formatted data.
A connector is a bridge when we have to connect a database with a programming language. It provides access to a database driver to the required language. Python MySQL installer available for different operating systems. You can download the MSI version from here -
The installer requires 'python.exe' in your system PATH, otherwise it will fail to install. So make sure to add Python in your system environment.
You can also install MySQL Connector using pip command.
pip install mysql-connector
First, we need to import the MySQL connector in the Python file to connect to the database. Then, use the connect() constructor to create a connection to the MySQL server. Make sure to replace the 'user', 'password', 'host' and 'database' with your database credentials.
import mysql.connector

conn = mysql.connector.connect(user='root', password='',
                              host='localhost',database='company')

if conn:
    print ("Connected Successfully")
else:
    print ("Connection Not Established")
Here is the MySQL select statement to fetch data from the 'employee' table.
mydict = create_dict()
select_employee = """SELECT * FROM employee"""
cursor = conn.cursor()
cursor.execute(select_employee)
result = cursor.fetchall()

for row in result:
    mydict.add(row[0],({"name":row[1],"email":row[2],"phone":row[3]}))
In the above code, first we have instantiated the create_dict class and called the add() method to store the fetched data in key-value pair. The class is defined as follows -
class create_dict(dict): 
  
    # __init__ function 
    def __init__(self): 
        self = dict() 
          
    # Function to add key:value 
    def add(self, key, value): 
        self[key] = value

import JSON
The JSON module provides dumps() method for writing data to files. This method takes a data object to be serialized, and the indent attribute specifies the indentation size for nested structures. The sort_keys attribute is a boolean value. If it is TRUE, then the output of dictionaries will be sorted by key.
stud_json = json.dumps(mydict, indent=2, sort_keys=True)

print(stud_json) 
Here, we have merged the above code that we explained in chunks to convert MySQL query result to JSON using Python.
import mysql.connector
import json

conn = mysql.connector.connect(user='root', password='',
                              host='localhost',database='company')

if conn:
    print ("Connected Successfully")
else:
    print ("Connection Not Established")

class create_dict(dict): 
  
    # __init__ function 
    def __init__(self): 
        self = dict() 
          
    # Function to add key:value 
    def add(self, key, value): 
        self[key] = value

mydict = create_dict()
select_employee = """SELECT * FROM employee"""
cursor = conn.cursor()
cursor.execute(select_employee)
result = cursor.fetchall()

for row in result:
    mydict.add(row[0],({"name":row[1],"email":row[2],"phone":row[3]}))

stud_json = json.dumps(mydict, indent=2, sort_keys=True)

print(stud_json)

The above code returns output in JSON format as follows -

Jan 3
Stateful vs Stateless
A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

Dec 29
Best programming language to learn in 2021
In this article, we have mentioned the analyzed results of the best programming language for 2021...

In this article, we have mentioned the analyzed results of the best programming language for 2021...

Dec 20
How is Python best for mobile app development?
Python has a set of useful Libraries and Packages that minimize the use of code...

Python has a set of useful Libraries and Packages that minimize the use of code...

July 18
Learn all about Emoji
In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

Jan 10
Data Science Recruitment of Freshers
In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...






eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.