在将其标记为重复之前,我想清楚地表明,我已经尝试过无数种解决方案来消除这种情况,方法是使用from __future__ import unicode_literals
来处理str.encode('utf8')
和{# -*- coding: utf-8 -*-
等等。我知道我做错了什么,所以我会尽可能的具体化,我正在把一个字典转换成一个JSON数组/对象,并在网页上以它的原始字符串形式显示出来。在
我遇到的问题是文件名中以“µ”开头的unicode字符串,因此错误发生在下面代码的最后四行。files
数组将该字符串索引处的值显示为\xb5激流.lnk。在
if os.path.isdir(finalDirPath):
print "is Dir"
for (path,dir,files) in os.walk(finalDirPath):
if dir!=[]:
for i in dir:
if not hidden(os.path.join(path,i)):
# Here
JSONarray.append({"ext":"dir","path":b64(os.path.join(path,i)),"name":i})
if files!=[]:
for i in files:
if not hidden(os.path.join(path,i)):
# Here
JSONarray.append({"ext":i.split('.')[-1],"path":b64(os.path.join(path,i)),"name":i})
break
jsonStr = {"json":json.dumps(JSONarray)}
return render(request,"json.html",jsonStr)
回溯如下:
^{pr2}$
用一个简短的例子来说明你的问题:
数组
files
包含字节字符串,但是json.dumps()
希望数据中的任何字符串都是unicode。它假设任何字节字符串都是utf-8编码的,但是字符串使用的是不同的编码:可能是latin1或其他的。在将所有文件名添加到JSONarray
结构之前,您需要找出文件系统使用的编码,并将所有文件名解码为unicode。在首先要检查文件系统编码:
^{pr2}$应该告诉您文件名使用的编码,然后确保所有路径操作都使用unicode:
相关问题 更多 >
编程相关推荐