0

I create a JSON file with special characters as strings.

I create for example a dict with

dict[u"Züge"] = ...
json.dump(dict, file)

When i view the dumped file it looks like this:

{
  "Z\u00fcge": [
    {

Is there a way to write to the file the encoding so that any text editor will automatically display the right characters?

i then get the following error:

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

quesaionasis
  • 137
  • 1
  • 2
  • 11

2 Answers2

0

You need to use ensure_ascii=False in your json.dump function :

dict[u"Züge"] = ...
json.dump(dict, file,ensure_ascii=False)

Character Encodings in Json:

As permitted, though not required, by the RFC, this module’s serializer sets ensure_ascii=True by default, thus escaping the output so that the resulting strings only contain ASCII characters.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

Specify ensure_ascii=False when calling json.dump:

json.dump(dict, file, ensure_ascii=False)
jwodder
  • 54,758
  • 12
  • 108
  • 124