#!/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)
最佳答案
发布完整的回溯,错误可能来自无法解码字典对象的打印语句。出于某种原因,如果其中包含西里尔文本,则 print 语句无法解码所有内容。
以下是我将包含西里尔字母的字典保存到 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')
关于arrays - Python如何将带有西里尔符号的字典保存到json文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33141120/