0
votes

I want to be able to view the file in the editor and see an automatically ü.

# -*- coding: utf-8 -*-
import json
from collections import OrderedDict

fdata = OrderedDict()
fdata[u"Züge"] = 0
fdata[u"Bahnhöfe"] = 0

with open("Desktop/test.json", "w") as outfile:
    json.dump(fdata, outfile, indent=2, ensure_ascii=False)

UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 2: ordinal not in range(128)

It has something to do with OrderedDict, with a normal dict it works.

2
Is the exception occurring only at runtime or you also have difficulty to display the character in a text editor ? - Laurent Jalbert Simard
it occurs when i try json.dumps() - apfel
Can you show us the code that opens 'file'? Have you specified an encoding? - oefe

2 Answers

0
votes

I had a similar issue once, I've added this line at the top of my .py file and it worked.

# coding=utf-8
0
votes

You don't specify an encoding when opening the file, so outfile.encoding is probably None.

file.encoding

The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. In addition, when the file is connected to a terminal, the attribute gives the encoding that the terminal is likely to use (that information might be incorrect if the user has misconfigured the terminal). The attribute is read-only and may not be present on all file-like objects. It may also be None, in which case the file uses the system default encoding for converting Unicode strings.

And your system default encoding is apparently ascii.

Instead, open your file with the desired encoding:

import codecs
  with codecs.open("test.json", "w", encoding='utf-8') as outfile: