Python JSON Unicode错误OrderedDi

2024-10-01 11:37:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够在编辑器中查看文件,并自动看到一个。在

# -*- 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)

它与有序的dict有关,与正常的dict有关。在


Tags: 文件infromimportjsonascii编辑器collections
2条回答

打开文件时没有指定编码,因此outfile.encoding可能是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.

你的系统默认编码显然是ascii。在

相反,请使用所需的编码打开文件:

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

我曾经遇到过类似的问题,我在我的.py文件的顶部添加了这一行,它起作用了。在

# coding=utf-8

相关问题 更多 >