20

I want to convert my dataframe to json and dump it in a file in a pretty print format. I tried -

df.to_json(r'C:\users\madhur\Desktop\example.json,'orient = 'index')

the above code is dumping in json but in a single line.

I also tried

import json
hello = df.to_json(orient = 'index')
with open(r'C:\users\madhur\Desktop\example.json','a') as f:
    json.dump(hello,f,indent=4,sort_keys=True)

but the above code is giving a single line output the the output has a '\' before the double inverted commas.

the output looks like -

"{\"17668620_INCOLL\":{\"DRWECNTRY\":\"NEW ZEALAND........"

if some one has any suggestions, answers or need any more information regarding this query then please comment/answer.

Note - I'm using Python 3.6

Madhur Yadav
  • 635
  • 1
  • 11
  • 30
  • Can you post some of your dataframe, some of your data, more of the JSON? – Evan Nov 28 '18 at 16:38
  • Related? https://stackoverflow.com/questions/28976546/write-pandas-dataframe-to-line-delineated-json – Evan Nov 28 '18 at 16:39

2 Answers2

22

you can directly pass indent = int :

df.to_json(r'example.json', orient='index', indent=2 )
Community
  • 1
  • 1
Rahul Palyekar
  • 244
  • 3
  • 4
3

Use df.to_dict(orient='records') if you want to simply be able to copy paste something from REPL

mathtick
  • 6,487
  • 13
  • 56
  • 101