Convert data from sqlalchemy rows into specific json structure

40 views Asked by At

This might seem like a trivial question, but I am struggling in framing a query so as to search in google, so hence decided to elaborate as clearly as possible here.

I have a flask application which connects to sqlite3 database using sqlalchemy. I am running a sql query which returns data as depicted below.

FACTORX FACTORY  FACTORZ
------- -------  -------
INPUT1  SUB-1    RES-1 
INPUT1  SUB-1    RES-2 
INPUT1  SUB-2    RES-1
INPUT1  SUB-2    RES-2 
INPUT2  SUB-1    RES-1 
INPUT2  SUB-1    RES-2 
INPUT2  SUB-2    RES-1 
INPUT2  SUB-2    RES-2 

What I want is output in json format like depicted below.

{
    "INPUT1": {[
        "SUB-1": {[
            "RES-1", "RES-2"
        ]},
        "SUB-2": {[
            "RES-1", "RES-2"
        ]}
    ]},
    "INPUT2": {[
        "SUB-1": {[
            "RES-1", "RES-2"
        ]},
        "SUB-2": {[
            "RES-1", "RES-2"
        ]}
    ]},
}

My question what is the best way to achieve the above desired format?

Thanks

0

There are 0 answers