【问题标题】:Python how to save dictionary with cyrillic symbols into json filePython如何将带有西里尔符号的字典保存到json文件中
【发布时间】:2016-01-13 11:22:00
【问题描述】:
#!/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' codec can't encode characters in position 1-5: ordinal not in range(128)

【问题讨论】:

    标签: arrays dictionary unicode


    【解决方案1】:

    发布完整的回溯,当它无法解码字典对象时,错误可能来自打印语句。如果你有西里尔文字,由于某种原因,打印语句无法解码所有内容。

    这是我将包含西里尔字母的字典保存到 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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-05
      • 2022-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 2013-04-26
      • 2018-04-10
      相关资源
      最近更新 更多