Bring a dataset with header into a specific json format with pandas
You can do this directly with pandas
:
df = pd.read_csv('path_to_file.txt', sep=';')
Output:
HeaderCol1 HeaderCol2 HeaderCol3
0 ValueRow1Col1 ValueRow1Col2 VRow1Col3
1 ValueRow2Col1 ValueRow2Col2 VRow2Col3
2 ValueRow3Col1 ValueRow3Col2 VRow3Col3
Then simply call:
df.to_json(orient='index')
Output:
'{"0":{"HeaderCol1":"ValueRow1Col1"," HeaderCol2":" ValueRow1Col2"," HeaderCol3":" VRow1Col3"},"1":{"HeaderCol1":"ValueRow2Col1"," HeaderCol2":" ValueRow2Col2"," HeaderCol3":" VRow2Col3"},"2":{"HeaderCol1":"ValueRow3Col1"," HeaderCol2":" ValueRow3Col2"," HeaderCol3":" VRow3Col3"}}'
EDIT
Reading from a buffer instead:
from io import StringIO
df = pd.read_csv(StringIO(rawdata), sep=';')