user3447653 user3447653 - 1 month ago 6x
JSON Question

Formatting json strings in Python

I have a query that runs and creates a dataframe like below:

Group Hour
G1 0
G1 4
G2 1
G3 5

I then write the dataframe to a json file using

out = df1.to_json(orient='records')[1:-1].replace('},{', '} {')

Currently my output looks like

{"Group":"G1","Hour":0} {"Group":"G2","Hour":4} {"Group":"G2","Hour":1}

It is a continuous stream of lines. I am trying to make each json document to be in a separate line like below:


Not sure whether there is a way to achieve this in Python. Any help would be appreciated.


Just change the .replace('},{', '} {') part to .replace('},{', '}\n{')?