LoginSignup
0
0

More than 3 years have passed since last update.

kivy JsonStore でUnicodeDecodeError を解決する

Last updated at Posted at 2020-09-23

問題のエラー

Kivyでstorageモジュールを使ってjsonを扱う際、以下のようなエラーに遭遇した。
※環境はpython3.8 ですが、大した差異はないと思います。

   File "C:\programing\project\hoge\main.py", line 33, in _init_load
     self.store = JsonStore('test.json', )
   File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\kivy\storage\jsonstore.py", line 29, in __init__
     super(JsonStore, self).__init__(**kwargs)
   File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\kivy\storage\__init__.py", line 134, in __init__
     self.store_load()
   File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\kivy\storage\jsonstore.py", line 43, in store_load
     data = fd.read()
 UnicodeDecodeError: 'cp932' codec can't decode byte 0x82 in position 85: illegal multibyte sequence

親の顔より見たUnicodeDecodeErrorですね。日本語が入ってることが原因ですかね?
このエラーは基本的にopen関数の引数にencoding='utf-8'を追加すれば解決できます。
というわけでstorageモジュールの中でjsonファイルを開く部分をサクッと変更します。
31行目に読み込みを行う関数があるので、そこのopen部分にキーワード引数を追加します。

kivy/storage/jsonstore.py
def store_load(self):
        if not exists(self.filename):
            folder = abspath(dirname(self.filename))
            if not exists(folder):
                not_found = IOError(
                    "The folder '{}' doesn't exist!"
                    "".format(folder)
                )
                not_found.errno = errno.ENOENT
                raise not_found
            return
        with open(self.filename, encoding='utf-8') as fd:    # ココ
            data = fd.read()
            if len(data) == 0:
                return
            self._data = loads(data)

結果

正常に読み込むことに成功しました。
日本語はややこしいですね。。。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0