简体   繁体   中英

Returning Oracle query results in JSON format

I want to create a python script to run an oracle query and store each resulting row into a JSON file. So far, I have completed the oracle connection, the query execution and the printing of each resulting row.

Note: I'm using cx_Oracle

import cx_Oracle

try:
    con = cx_Oracle.connect('username/pass@127.0.0.1/oracle')
except cx_Oracle.DatabaseError as er:
    print('There is an error in the Oracle database:', er)

else:
    try:
        cur = con.cursor()

        # fetchall() is used to fetch all records from result set
        cur.execute('select * from products')
        rows = cur.fetchall()
        print(rows)


    except cx_Oracle.DatabaseError as er:
        print('There is an error in the Oracle database:', er)

    except Exception as er:
        print('Error:'+str(er))

    finally:
        if cur:
            cur.close()
finally:
    if con:
        con.close()

The following is the desired JSON output:

product_json

{
    "arrayOfProducts": [
        {
            "id": 1,
            "name": "CHECK PRINT SHIRT",
            "price": 110
        },
        {
            "id": 2,
            "name": "GLORIA HIGH LOGO SNEAKER",
            "price": 91
        },
        {
            "id": 3,
            "name": "CATE RIGID BAG",
            "price": 94.5
        },
        {
            "id": 4,
            "name": "GUESS CONNECT WATCH",
            "price": 438.9
        }
    ]
}

Instead of using select * from products , you can get the JSON from the database using:

SELECT JSON_OBJECT(
         KEY 'arrayOfProducts'
         VALUE JSON_ARRAYAGG(
           JSON_OBJECT(
             KEY 'id'    VALUE id,
             KEY 'name'  VALUE name,
             KEY 'price' VALUE price
             -- RETURNING CLOB PRETTY
           )
           -- RETURNING CLOB PRETTY
         )
         -- RETURNING CLOB PRETTY
       ) AS json
FROM   products

(Note: uncomment the RETURNING CLOB PRETTY lines if you want it formatted with white space.)

Which, for the sample data:

CREATE TABLE products (id, name, price) AS
SELECT 1, 'name1', 110   FROM DUAL UNION ALL
SELECT 2, 'name2',  91   FROM DUAL UNION ALL
SELECT 3, 'name3',  94.5 FROM DUAL UNION ALL
SELECT 4, 'name4', 438.9 FROM DUAL;

Outputs:

JSON
{"arrayOfProducts":[{"id":1,"name":"name1","price":110},{"id":2,"name":"name2","price":91},{"id":3,"name":"name3","price":94.5},{"id":4,"name":"name4","price":438.9}]}

db<>fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM