How to convert MySQL query result to JSON in Python
In this article, you will learn a simple process to convert MySQL query results to JSON using the Python programming.
JSON (JavaScript Object Notation) is a lightweight, open standard file format. It is easy for humans to read and write. 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.
Install MySQL Connector
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-
Python MySQL InstallerThe installer requires 'python.exe' in your system PATH; otherwise, it will fail to install. So make sure to add Python to your system environment.
You can also install MySQL Connector using the pip command.
pip install mysql-connector
Python connecting to MySQL
First, we need to import the MySQL connector into 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")
Python MySQL Select Table
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 a 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 Module
import JSON
The JSON module provides the 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)
Complete Code: Convert MySQL query result to JSON
Here, we have merged the above code that we explained in chunks to convert the MySQL query results to JSON using the Python programming language.
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-
Related Articles
CRUD operations in Python using MongoDB connectorPython read JSON from URL requests
Python convert XML to JSON
Insert JSON data into MongoDB using Python
Python requests POST method
Convert MongoDB Document to JSON using Python
Python Pandas DataFrame
Python3 Tkinter Messagebox
Python get visitor information by IP address
Python Webbrowser
Python Tkinter Overview and Examples
Python Turtle Graphics Overview
Factorial Program in Python
Python snake game code with Pygame
Python JSON Tutorial - Create, Read, Parse JSON file
Python convert xml to dict
Python convert dict to xml
How to convert python list to numpy array
Shuffle list python
Print hollow diamond pattern in Python
Python double asterisk