0

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/[email protected]/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
        }
    ]
}
1
  • 1
    Now you have the data, have a look at other StackOverflow posts which give solutions about writing to files in Python. Commented Mar 1, 2022 at 23:39

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.