简体   繁体   中英

Why do I get a ValueError with Json using a windows txt file encoded with utf-8?

Here's the method:

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

Here's the file (Which was saved with utf-8 encoding):

{
"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 "
}

And here's the error:

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

If I encode it as "ANSI", this error goes away. I don't understand, char 0 is {.

BOM must be the culprit. Open the file with codecs.open(path,"r","utf-8-sig") or autodetect the encoding to open with eg as per Reading Unicode file data with BOM chars in Python .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM