Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Json API
#2
This has nothing to do with JSON. Your query returns a list of lists. You pass the list to json.dump(), json writes the list of lists to the file. If you want JSON to write a list of dictionaries, you need to pass a list of dictionaries to json.dump. A database query will not return a dictionary, so you'll have to get the query results, which will be values in your dictionary, and pair them with the table column names, which are the keys.

Something like this (untested)
import oracledb as db
import json

db.init_oracle_client()
con = db.connect(connectinfo)
cur = con.cursor()
columns = ('emp_no', 'first_name', 'salary', 'dept_no')
rows = []
for row in cur.execute(f'select {", ".join(columns)} from emp'):
    rows.append(dict(zip(columns, row)))
with open("emp.json", "w") as file:
    json.dump(rows, file, indent=6)
Reply


Messages In This Thread
Json API - by JayPy - Mar-02-2024, 08:25 PM
RE: Json API - by deanhystad - Mar-02-2024, 09:32 PM
RE: Json API - by JayPy - Mar-04-2024, 12:55 PM
RE: Json API - by buran - Mar-03-2024, 05:18 AM
RE: Json API - by deanhystad - Mar-04-2024, 04:28 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020