I'm reading a csv file that contains Hebrew, I'm doing some manipulations and then…
- User
I'm reading a csv file that contains Hebrew, I'm doing some manipulations and then saving it into a json file. When I open the json file, instead of Hebrew letters I have stuff like "\u05d1\u05e9\u05d9\u05dd \u05dc\u05d8\u05d1\u05d7,\u2" How can I fix it?
Assistant
The issue you're seeing is that the Hebrew text is being Unicode-escaped in your JSON file. The characters like \u05d1 are the Unicode code points for Hebrew letters, which is technically correct but not human-readable. To fix this, you need to disable ASCII encoding when writing the JSON file. Here's how: In Python: pythonimport json
When writing the JSON, use ensure_ascii=False
with open('output.json', 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) In JavaScript/Node.js: javascriptconst fs = require('fs');
// JSON.stringify already preserves Unicode by default fs.writeFileSync('output.json', JSON.stringify(data, null, 2), 'utf-8'); The key points are:
ensure_ascii=False (Python) - This tells Python not to escape non-ASCII characters encoding='utf-8' - Ensures the file is written in UTF-8 encoding Make sure you're also reading the CSV with UTF-8 encoding
For reading the CSV with UTF-8: pythonimport pandas as pd df = pd.read_csv('input.csv', encoding='utf-8')
Or with built-in csv module
import csv with open('input.csv', 'r', encoding='utf-8') as f: reader = csv.DictReader(f) data = list(reader) If you share the specific code you're using, I can give you more targeted advice!
- User
This is my current code, I'm not using dump:share_lm_formatted_dataset = pd.DataFrame(examples) print(share_lm_formatted_dataset.shape) share_lm_formatted_dataset.to_json('share_lm_formatted_04.json', orient='records', default_handler=str)
Assistant
Perfect! The issue is with pandas.to_json(). You need to add the force_ascii=False parameter: pythonshare_lm_formatted_dataset = pd.DataFrame(examples) print(share_lm_formatted_dataset.shape) share_lm_formatted_dataset.to_json('share_lm_formatted_04.json', orient='records', force_ascii=False, default_handler=str) By default, pandas.to_json() uses force_ascii=True, which escapes all non-ASCII characters (like Hebrew). Setting it to False will preserve the Hebrew characters in their readable form. Also, if you want pretty-printed JSON (with indentation), you can add: pythonshare_lm_formatted_dataset.to_json('share_lm_formatted_04.json', orient='records', force_ascii=False, default_handler=str, indent=2) This will make your JSON file much more readable!