I have JSON data that has strings that may contain "\n" linebreaks:
{
"Id": 12345,
"firstname": "Peter",
"lastname": "Normalname"
},
{
"Id": 76890,
"firstname": "Paul",
"lastname": "Evil\nLinebreak" # here's the \n
},
I'm trying to write this to a CSV file using Python 3. This is my approach:
def write_csv_file(filename, resp):
# open file
csvFile = open(filename, "w", newline='', encoding='utf-8')
csvWriter = csv.writer(csvFile, delimiter=',', quoting=csv.QUOTE_ALL)
# write data
for line in resp:
csvWriter.writerow(line.values())
# close file
csvFile.close()
Now my problem is that the \n character messes up my CSV file by adding an unexpected line break.
So instead of
"76890","Paul","Evil\nLinebreak"
I get
"76890","Paul","Evil
Linebreak"
What's the best way to solve this, ideally without changing the data, i.e., maintaining the \n character, but without breaking the CSV structure.
Any hints are greatly appreciated.