【问题标题】:Why do I get a ValueError with Json using a windows txt file encoded with utf-8?为什么我使用 utf-8 编码的 windows txt 文件在 Json 中得到 ValueError?
【发布时间】:2015-12-26 07:23:20
【问题描述】:

方法如下:

def load(self, path):
        json_data = open(path, "r")
        self.data = load(json_data)
        return self.data

这是文件(使用 utf-8 编码保存):

{
"False": "Falso",
"None": "Nulo",
"True": "Verdadeiro",
"as": "como",
"assert": "afirmar",
"break": ["quebrar", "interromper", "parar"],
"class": "classe",
"continue": "continuar",
"def": ["func", " f ", "função"],
"del": ["deletar", "excluir"],
"elif": ["senão se", "senao se"],
"else": ["senão", "senao"],
"except": ["exceto", "excetuar"],
"finally": "finalmente",
"for ": "para ",
"from ": "de ",
"if ": ["se ", "caso "],
"if(": ["se(", "caso("],
"import": "importar",
" in ": [" em ", " no ", " na ", " nos ", " nas "],
" is ": " é ",
"nonlocal": "nãolocal",
" not ": " não ",
" or ": " ou ",
"pass": ["passar", "prosseguir"],
"raise": ["levantar", "erguer"],
"return": "retornar",
"try": "tentar",
"while": "enquanto",
"with": "com",
"print": ["escrever", "imprimir", "printar", "mostrar"],
" and ": " e "
}

这是错误:

ValueError: Expecting value: line 1 column 1 (char 0)

如果我将它编码为“ANSI”,这个错误就会消失。我不明白,char 0 是 {.

【问题讨论】:

标签: python json python-3.x encoding utf-8


【解决方案1】:

BOM 一定是罪魁祸首。使用codecs.open(path,"r","utf-8-sig") 打开文件或自动检测要打开的编码,例如根据Reading Unicode file data with BOM chars in Python

【讨论】:

    猜你喜欢
    • 2015-01-07
    • 2012-05-08
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 2012-09-19
    • 1970-01-01
    相关资源
    最近更新 更多