python - mongodb插入显示 'strings in documents must be valid UTF-8'

标签 python mongodb utf-8

这是我的代码

        for code, data in dict_data.items(): 

            try:
                collection2.insert({'_id':code,'data':data})

            except Exception as e:
                print code,'>>>>>>>', str(e)
                sys.exit()

它退出了

         524715 >>>>>>> strings in documents must be valid UTF-8

我只能通过try catch方法找出错误。 dict_data 是一个大型字典,其中包含来自其他集合的计算值。

我该如何解决这个问题?

谢谢

最佳答案

如果您使用 PyMongo 和 Python 2.x,则应在 utf-8 或 unicode 字符串中使用 str。看: http://api.mongodb.org/python/current/tutorial.html#a-note-on-unicode-strings

如果data是一个包含多个字符串的字典,您可以使用以下函数将它们全部转换为unicode:

def convert2unicode(mydict):
    for k, v in mydict.iteritems():
        if isinstance(v, str):
            mydict[k] = unicode(v, errors = 'replace')
        elif isinstance(v, dict):
            convert2unicode(v)

for code, data in dict_data.items(): 
    try:
        convert2unicode(data)
        collection2.insert({'_id':code,'data': data})
    except Exception as e:
        print code,'>>>>>>>', str(e)
        sys.exit()

之前的代码会将所有 str 值转换为 unicode,“键”保持不变,根据根本原因,您还应该转换“键”。

关于python - mongodb插入显示 'strings in documents must be valid UTF-8',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22474701/

相关文章:

mysql - utf8_unicode_ci 在 mysql 中支持土耳其语吗?

python - psycopg2.DataError : invalid byte sequence for encoding "UTF8": 0xa0

java - 将字符串内容解析为二进制,然后在 Java 中转换为字符串

python - 在 Python 中使用 while 循环打印功率表

python - 使用 'value' 作为主键和 'key' 作为辅助键对 python 字典进行排序

javascript - MongoDB shell,$pop 运行异常

mongodb - 使用 Mongoose 中间件查找在任一字段中值匹配的文档

python - 如何通过 Python 使用亚马逊产品广告 API 5?

Python——输出文件中的数据位于不方便的位置

node.js - 使用 populate 查询两个模式