-1

我正在使用 pymongo 在集合中插入一个复杂的结构作为一行。该结构是字典列表的字典列表等的字典。

有没有办法找到哪个字段是unicode而不是str,这会导致错误?我努力了:

def dump(obj):
  with open('log', 'w') as flog:
    for attr in dir(obj):
      t, att = type(attr), getattr(obj, attr)
      output =  "obj.%s = %s" % (t, att)
      flog.write(output)

但到目前为止还没有运气。

有什么聪明的递归方式可以打印所有东西吗?

谢谢

4

1 回答 1

0

以下帮助我找出哪个 dict 包含 unicode 值,因为 dict 可以通过它的键来识别。列表案例没有帮助。

def find_the_damn_unicode(obj):

    if isinstance(obj, unicode):
        ''' The following conversion probably doesn't do anything meaningfull since
            obj is probably a primitive type, thus passed by value. Thats why encoding
            is also performed inside the for loops below'''
        obj = obj.encode('utf-8')
        return obj

    if isinstance(obj, dict):
        for k, v in obj.items():
            if isinstance(v, unicode):
                print 'UNICODE value with key ', k
                obj[k] = obj[k].encode('utf-8')
            else:
                obj[k] = find_the_damn_unicode(v)

    if isinstance(obj, list):
        for i, v in enumerate(obj):
            if isinstance(v, unicode):
                print 'UNICODE inside a ... list'
                obj[i] = obj[i].encode('utf-8')
            else:
                obj[i] = find_the_damn_unicode(v)

    return obj
于 2015-03-31T10:23:04.323 回答