Python如何将带有西里尔符号的字典保存到json文件中

时间:2015-10-15 06:12:50

标签: arrays dictionary unicode

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json


d = {'a':'текст',
     'b':{
         'a':'текст2',
         'b':'текст3'
     }}
print(d)

w = open('log', 'w')
json.dump(d,w, ensure_ascii=False)
w.close()

它给了我: UnicodeEncodeError:'ascii'编解码器不能编码1-5位的字符:序号不在范围内(128)

1 个答案:

答案 0 :(得分:2)

发布完整的回溯,当错误解码字典对象时,错误可能来自print语句。出于某种原因,如果您在其中包含西里尔文本,则print语句无法解码所有内容。

以下是我如何将包含Cyrillics的字典保存到json:

mydictionary = {'a':'текст'}
filename = "myoutfile"
with open(filename, 'w') as jsonfile:
     json.dump(mydictionary, jsonfile, ensure_ascii=False)

诀窍是将json读回字典并用它做事。

将json读回字典:

with open(filename, 'r') as jsonfile:    
newdictonary = json.load(jsonfile)

现在,当你查看字典时,'текст'这个词看起来(编码)就像'\ u0442 \ u0435 \ u043a \ u0441 \ u0442'。您只需要使用encode('utf-8')解码它:

for key, value in newdictionary.iteritems():
       print value.encode('utf-8')

如果您的西里尔文本存储在那里,列表也是如此:

for f in value:
    print f.encode('utf-8')
    # or if you plan to use the val somewhere else:
    f = f.encode('utf-8')