Python Parse Oracle DDL and Generate JSON Data

297 views Asked by At

I have a requirement where i need to parse a DDL from Oracle table and generate a JSON data out of it. For that i had used DDL parser in Python to convert it to string however i couldnt able to get it as JSON Data as such.

import json

from ddlparse import DdlParse

sample_ddl = """
CREATE TABLE SCOTT.EMPLOYEE (   
EMP_NO VARCHAR2(5 CHAR) NOT NULL , 
    EMP_NAME VARCHAR2(50 CHAR) NOT NULL , 
    CONSTRAINT EMP_PK PRIMARY KEY (EMP_NO)
);
"""

# parse pattern (1-2) : Specify source database
table = DdlParse().parse(ddl=sample_ddl, source_database=DdlParse.DATABASE.oracle)


print("* COLUMN *")
for col in table.columns.values():
     
    col_info = {}

    #col_info["table:name"]            = table.name
    col_info["name"]                  = col.name
    col_info["data_type"]             = col.data_type
    col_info["length"]                = col.length
    col_info["precision(=length)"]    = col.precision
    col_info["scale"]                 = col.scale
    col_info["not_null"]              = col.not_null
    col_info["PK"]                    = col.primary_key
    col_info["bigquery_field"]        = json.loads(col.to_bigquery_field())   

    print(json.dumps(col_info, indent=2, ensure_ascii=False))

For the above code the Output is coming as string but not as a JSON data as it should look below. I need the out in JSON Data format as

  {
    "name": "EMP",
    "columns":
    [
        {
            "name": "EMP_NO",
            "dataType": "VARCHAR2(5 CHAR) ",
            "nullable": false
        },
        {
            "name": "EMP_NAME",
            "dataType": "VARCHAR2(50 CHAR)",
            "nullable": false
        }
    ],
    "primaryKey":
    [
        "EMP_NO"
    ]
}

Any help will be highly appreciated.

Thanks

0

There are 0 answers