0

I created an API using FastAPI that returned a JSON. First, I used to turn the Dataframe to JSON using the Pandas .to_json() method, which allowed me to choose the correct "orient" parameter. This saved a .json file and then opened it to make fastAPI return it as it follows:

DATA2.to_json("json_records.json",orient="records")

with open('json_records.json', 'r') as f:
data = json.load(f)

return(data)

This worked perfectly, but i was told that my script shouldn't save any files since this script would be running on my company's server, so I had to directly turn the dataframe into JSON and return it. I tried doing this:

data = DATA2.to_json(orient="records")

return(data)

But now the API's output is a JSON full of "\". I guess there is a problem with the parsing but i can't really find a way to do it properly. The output now looks like this:

"[{\"ExtraccionHora\":\"12:53:00\",\"MiembroCompensadorCodigo\":117,\"MiembroCompensadorDescripcion\":\"OMEGA CAPITAL S.A.\",\"CuentaCompensacionCodigo\":\"1143517\",\"CuentaNeteoCodigo\":\"160234117\",\"CuentaNeteoDescripcion\":\"UNION FERRO SRA A\",\"ActivoDescripcion\":\"X17F3\",\"ActivoID\":8,\"FinalidadID\":2,\"FinalidadDescripcion\":\"Margenes\",\"Cantidad\":11441952,\"Monto\":-16924935.3999999985,\"Saldo\":-11379200.0,\"IngresosVerificados\":11538288.0,\"IngresosNoVerificado\":0.0,\"MargenDelDia\":0.0,\"SaldoConsolidadoFinal\":-16765847.3999999985,\"CuentaCompensacionCodigoPropia\":\"80500\",\"SaldoCuentaPropia\":-7411284.3200000003,\"Resultado\":\"0\",\"MiembroCompensadorID\":859,\"CuentaCompensacionID\":15161,\"CuentaNeteoID\":7315285}.....

What would be a proper way of turning my dataframe into a JSON using the "records" orient, and then returning it as the FastAPI output? Thanks!

  • Does this answer your question? [How to return a csv file/Pandas DataFrame in JSON format using FastAPI?](https://stackoverflow.com/questions/71203579/how-to-return-a-csv-file-pandas-dataframe-in-json-format-using-fastapi) – Chris Feb 01 '23 at 07:21

1 Answers1

0

update: i changed the to_json() method to to_dict() using the same parameters and seems to work... don't know if its correct.

    data = DATA2.to_dict(orient="records")

return(data)