2017-01-04 3 views
0

これを複製としてマークする前に、私はfrom __future__ import unicode_literalsをすべてに使用することによって、ファイルの先頭に# -*- coding: utf-8 -*-とすると、str.encode('utf8')str.decode('utf8')の組み合わせと組み合わせはありません。できるだけ具体的になるように何かが間違っていることは知っています。辞書をJSON Array/Objectに変換し、それをWebページ上の生の文字列形式で表示しています。'utf8'コーデックは、位置0のバイト0xb5をデコードできません:無効な開始バイト

私が発行しているユニコード文字列は、ファイル名に「μ」で始まる文字列なので、下のコードの最後の4行目にエラーが発生します。配列filesは、その文字列のインデックスにある値を\ xb5Torrent.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) 

は、トレースバックです:

Traceback (most recent call last): 
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner 
response = get_response(request) 
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response 
response = self._get_response(request) 
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response 
response = self.process_exception_by_middleware(e, request) 
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response 
response = wrapped_callback(request, *callback_args, **callback_kwargs) 
File "E:\ICT\Other\Python\Django\trydjango18\src\newsletter\views.py", line 468, in getJSON 
JSONarray.append({"ext":i.split('.')[-1],"path":b64(os.path.join(path.encode('utf8'),i)),"name":i}) 
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb5 in position 0: invalid start byte 
+3

ことができますトレースバックを追加してください。 – snakecharmerb

+0

また、 'b64'関数はどこから来ますか?そのソースコードはありますか? – snakecharmerb

+0

@snakecharmerb追加され、b64関数はbase64.b64encode()関数です。 –

答えて

3

あなたの問題を示して短い例:

>>> json.dumps('\xb5Torrent.lnk') 

Traceback (most recent call last): 
    File "<pyshell#17>", line 1, in <module> 
    json.dumps('\xb5Torrent.lnk') 
    File "C:\Python27\lib\json\__init__.py", line 243, in dumps 
    return _default_encoder.encode(obj) 
    File "C:\Python27\lib\json\encoder.py", line 201, in encode 
    return encode_basestring_ascii(o) 
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb5 in position 0: invalid start byte 

あなたの配列filesは、バイト文字列が含まれていますが、json.dumps()はデータ内の任意の文字列があることを望んでいますユニコード。これは、任意のバイト文字列がutf-8でエンコードされていると仮定していますが、文字列が異なるエンコーディングを使用している可能性があります。あなたのファイルシステムで使用されているエンコーディングを見つけ出し、JSONarray構造体に追加する前に、すべてのファイル名をデコードしてユニコードにする必要があります。

まず最初は、ファイルシステムのエンコーディングをチェックすることです:

import sys 
print sys.getfilesystemencoding() 

はあなたのファイル名に使用するエンコーディングを伝える必要があり、その後、あなただけのすべてのパスの操作はユニコードを使用していることを確認してください:

import sys 
fsencoding = sys.getfilesystemencoding() 
if os.path.isdir(finalDirPath): 
    print "is Dir" 
    for (path,dir,files) in os.walk(finalDirPath): 
     path = path.decode(fsencoding) 
     for i in dir: 
      i = i.decode(fsencoding) 
      if not hidden(os.path.join(path,i)): 
       # Here 
       JSONarray.append({ 
        "ext": "dir", 
        "path": b64(os.path.join(path,i)), 
        "name": i}) 
       }) 

     for i in files: 
      i = i.decode(fsencoding) 
      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) 
+0

そして、どうすれば正確に行うことができますか? –

+0

@ Mr.Robotサンプルコードが追加されました。 – Duncan

+0

それは働いた!コードをデコードした後にbase64文字列を受け取ったときに、コードの別の場所にコードを戻すだけでした。将来のためにこのソリューションを覚えています。ありがとうございました。 –

関連する問題