jsonpython-polarspolars

Column oriented JSON from Polars DF


Good morning,

I'm trying to convert a polars df to a json object (in python), but i can't seem to find a way to change the format of it between row/col orientation. In Pandas, by default, it creates a column-oriented JSON object, and it can be changed easily, but in Polars it's row-oriented and i can't seem to find a way to change that, since the write_json method doesn't actually receives any arg other than the target filename if u wanna save it directly.

Any idea how to achieve that?

Thanks in advance!


Solution

  • To achieve a column-oriented JSON structure, You need to transform the DataFrame to a Dictionary before exporting Example:

    import polars as pl
    import json
    
    df = pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
    # json_data = df.write_json() # I guess you have tried this
    
    # Convert to column-oriented JSON
    # json_data = json.dumps(df.to_dict(as_series=False), indent=4)
    
    # Convert to column-oriented JSON without newlines
    json_data = json.dumps(df.to_dict(as_series=False), separators=(',', ':')) 
    print(json_data)
    

    Output: {"A": [1, 2, 3], "B": [4, 5, 6]}