Home > Software design >  python convert dataframe to json with \n
python convert dataframe to json with \n

Time:11-24

We converted dataframe to json using to_json(), but \n disappears in the string. How can I convert while keeping \n?
Before conversion, dataframe has \n, which disappears when converted

now:

companyId:"ckurudq3r00efkakh4hgu33pn"
tagName:
contact:"0336443303"
phone:"01066449675"
virtualNumber:"050413736583"
partner:false
certificate:false
memo:null
businesshours:"Mon~Fri: 09:00AM ~ 06:00PM Sat: 09:00AM ~ 06:00PM Sun: 09:00AM ~ 06:00PM"

what i want:

companyId:"ckurudq3r00efkakh4hgu33pn"
tagName:
contact:"0336443303"
phone:"01066449675"
virtualNumber:"050413736583"
partner:false
certificate:false
memo:null
businesshours:"Mon~Fri: 09:00AM ~ 06:00PM\nSat: 09:00AM ~ 06:00PM\nSun: 09:00AM ~ 06:00PM"

CodePudding user response:

I was running through something similar to this and I do not remember that I could figure it out so I came up with a workaround.

#replace '\n' with '\\n'
df.replace('\n', '\\n', inplace= True)
# export normally
df.to_json('path')

whenever you want to open it back, just read the file and again replace any '\\n' with '\n'

  • Related