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

标签 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)

最佳答案

发布完整的回溯,错误可能来自无法解码字典对象的打印语句。出于某种原因,如果其中包含西里尔文本,则 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/

相关文章:

python - 从 Pandas 文本中删除unicode

Python 函数式方法 : remove key from dict using filter

Python:从具有唯一名称的文件创建多个空字典

javascript - 在 pug (jade) 和 Node.js 中迭代两个数组

arrays - 如何通过删除 "()"将我的字符串值更改为数组

java - 哪种方法是最好的?

python - 使用 python json.loads 解析 unicode 输入

android - 在Flutter文本中添加特殊字符如何在Flutter中显示文本中的特殊字符?

ios - 从 Firebase (Swift 3) 检索和读取数据作为 NSArray

c++ - 如何在编译时初始化一个 constexpr 多维数组?