Home > OS >  problem in encoding .csv file content conversion to .json file
problem in encoding .csv file content conversion to .json file

Time:03-27

I use this piece of code to convert a .csv file content to a .json file:

import csv
import json

with open('export.csv', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

with open('test.json', 'w', encoding='utf-8') as f:
    json.dump(rows, f)

The conversion is successful, but Arabic characters in .csv file convert to something like this in .json file:

"\u06a9\u0627"

How can I solve this?

CodePudding user response:

According to json.dump docstring:

If ensure_ascii is false, then the strings written to fp can contain non-ASCII characters if they appear in strings contained in obj. Otherwise, all such characters are escaped in JSON strings.

Solution:

json.dump(rows, f, ensure_ascii=False)
  • Related