Sto elaborando un file UTF-8 in Python e ho usato simplejson per caricarlo in un dizionario. Tuttavia, sto diventando un UnicodeDecodeError quando cerco di trasformare uno dei valori del dizionario in una stringa:Python: perché str() su un testo da un file UTF-8 fornisce un errore UnicodeDecodeError?
f = open('my_json.json', 'r')
master_dictionary = json.load(f)
#some json wrangling, then it fails on this line...
mysql_string += " ('" + str(v_dict['code'])
Traceback (most recent call last):
File "my_file.py", line 25, in <module>
str(v_dict['code']) + "'), "
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf4' in position 35: ordinal not in range(128)
Perché Python anche utilizzando ASCII? Pensavo usasse UTF-8 di default e l'input provenga da un file UTF-8.
$ file my_json.json
my_json.json: UTF-8 Unicode English text
Qual è il problema?
Grazie! Per codificare tutti gli elementi nel dizionario, ho fatto: per k, v in v_dict.iteritems(): if v_dict [k]: v_dict [k] = v_dict [k] .encode ('utf-8') – AP257