オプションのindent
を指定すればOK
df.to_json('example.json', orient='index', indent=2 )
ちなみに、JSONがひらがな等の非ascii文字を含む場合は出力時にUnicodeエスケープされてしまうが、これを回避したい場合はオプションにforce_ascii=False
を追加すれば良い。
df.to_json('example.json', orient='index', indent=2, force_ascii=False)
関連リンク
ドキュメント: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html
stackoverflow: https://stackoverflow.com/questions/53523083/how-to-write-dataframe-in-json-in-pretty-print-style