Quick notes “How to write UTF-8 JSON content to file, no \u escape using Python 3

Ellery Leung
1 min readAug 14, 2019

--

Here is a quick note to this question: How to write a JSON Unicode (e.g. in Chinese) string to a file, without Python 3 json module to convert your string to \u escaped string.

Searching on Google I found that there are a lot of Python 2 syntax which is not applicable to Python3. So I decided to write this for reference to other people.

Here is the example.

with open(your_filename, 'r') as f:    # Read file to a variable
json_content = json.loads(f.read())
# Write json_content to file.
# Remember it is loaded by json.loads()
with open(new_filename, 'w+') as nf:
data= json.dumps(json_content, ensure_ascii=False)
nf.write(data)
nf.close()

2 key points to note here:

  1. I am using ensure_ascii=False to tell JSON not to convert my string. But that is not enough. So there is…
  2. I am NOT using json.dumps(json_content, <file_handler>) because it did not work for me. So I save json.dumps to a variable first, and then use `<file_handler>.write(data)` to solve it.

That makes a completed solution, for me.

Hope it helps someone.

--

--