简体   繁体   中英

While converting json to tsv( “\t” is my delimineter) there are new line character in values, How do i get rid of them

Code

import json
import csv

with open('output.tsv', 'w') as output_file, open('data.json') as data_file:    
    j = json.load(data_file)
    dw = csv.DictWriter(output_file, sorted(j[0].keys()), delimiter='\t')
    dw.writeheader()
    dw.writerows(j)

Data

[{"x" : "jkafadsnkas", "y" : "sa,nn\n"},{"x" : "jkaf\nadsnkas", "y" : "sa,nn\n"}]

Output

x   y

jkafadsnkas "sa,nn
"

"jkaf
adsnkas"    "sa,nn
"

Wanted Output

x   y


"jkafadsnkas    "sa,nn"

"jkafadsnkas"   "sa,nn"

I want that new line character must be stripped of from the data while writing in the tsv

In the data json I see you have \\n you should strip it first you can do that by

data = {k:data[k].strip() for k in data}

than you can feed this into the csvWriter do it after you load the json

To get what you want, I modify the code as follows:

import json
import csv

with open('output.tsv', 'w') as output_file, open('data.json') as data_file:
    j = json.load(data_file)
    j = [{k: v.replace('\n', '') for k, v in jj.items()} for jj in j]
    dw = csv.DictWriter(output_file, sorted(j[0].keys()), delimiter='\t')
    dw.writeheader()
    dw.writerows(j)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM