DB cursor.fetchall() convert ot custom model object

22 views
Skip to first unread message

Shreyansh jain

unread,
Jun 18, 2024, 1:37:15 AM (6 days ago) Jun 18
to Django REST framework
I want to convert my cursor.fetchall() response to JSON object.

Like example:
[
{Name: "XYZ-1", Address: "ABC-1"},
{Name: "XYZ-2", Address: "ABC-2"}  
]

currenty I am getting like below
[
["XYZ-1","ABC-1"],
["XYZ-2","ABC-2"]
]

Please help me how to parse in my custom models

Krishna Maru

unread,
Jun 18, 2024, 7:36:30 AM (5 days ago) Jun 18
to Django REST framework

import sqlite3
import json

# Reconnect to the SQLite database
conn = sqlite3.connect('example.db')
cur = conn.cursor()

# Execute the query
cur.execute("SELECT Name, Address FROM your_table")

# Fetch all rows from the executed query
rows = cur.fetchall()

# Get column names from the cursor description
column_names = [desc[0] for desc in cur.description]

# Convert the fetched rows to a list of dictionaries
result = [dict(zip(column_names, row)) for row in rows]

# Convert the list of dictionaries to a JSON object
json_result = json.dumps(result, indent=2)

print(json_result)

# Close the cursor and connection
cur.close()
conn.close()


try this one, because  i am hoping that your using sqlite3
Reply all
Reply to author
Forward
0 new messages