I have a pipe delimited file I am trying to convert to json using python (2.7). The code reads the text file, converts it based on the delimiter and then converts it to json.
When I run the code, the output in my terminal window is correct. However, when I write to a file the escape slashes \ are being added to the output. And quotation marks with no escapes are being added to the beginning and end of output file.
Based on other answers I've tried setting ensure_ascii to false each time I deal with the json dump. But that's not working.
input.txt:
392|0|9
Code:
import csv
import json
f = open( 'input.txt', 'rU')
reader = csv.DictReader( f, fieldnames = ( "A", "B", "C" ), delimiter='|')
out = json.dumps([ row for row in reader ], ensure_ascii=False)
print out
with open('data.json', 'w') as outfile:
json.dump(out, outfile, ensure_ascii=False)
Output in terminal:
[{"A": "392", "C": "9", "B": "0"}]
Output in data.json:
"[{\"A\": \"392\", \"C\": \"9\", \"B\": \"0\"}]"
I'm new to Python. What can I do to remove the quotation marks (at the start and end) and the slashes from the .json file?