Jupyter 无法打开 json 文件,引用 UnicodeDecodeError

问题描述 投票:0回答:1

Jupyter 在尝试打开目录中的 JSON 文件时抛出 UnicodeDecodeError。错误:

---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
Cell In[13], line 2
      1 with open('recalls.json') as file:
----> 2     json_data = json.load(file, encoding='utf-8')

File ~\AppData\Local\Programs\Python\Python312\Lib\json\__init__.py:293, in load(fp, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    274 def load(fp, *, cls=None, object_hook=None, parse_float=None,
    275         parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    276     """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
    277     a JSON document) to a Python object.
    278 
   (...)
    291     kwarg; otherwise ``JSONDecoder`` is used.
    292     """
--> 293     return loads(fp.read(),
    294         cls=cls, object_hook=object_hook,
    295         parse_float=parse_float, parse_int=parse_int,
    296         parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

File ~\AppData\Local\Programs\Python\Python312\Lib\encodings\cp1252.py:23, in IncrementalDecoder.decode(self, input, final)
     22 def decode(self, input, final=False):
---> 23     return codecs.charmap_decode(input,self.errors,decoding_table)[0]

UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 172381: character maps to <undefined>

我正在尝试打开一个 JSON 文件,最终将其转换为 CSV。该文件是本地的并上传到 Jupyter。我已经设置了编码,在 Chrome 上它显示其编码是 utf-8,但我仍然抛出错误。我还应该尝试其他编码吗?

这是我正在使用的代码:

import pandas as pd
import json

with open('recalls.json') as file:
    json_data = json.load(file, encoding='utf-8')
python json csv encoding jupyter
1个回答
0
投票

我认为你应该在打开文件时指明编码:

with open('recalls.json', encoding='utf-8') as f:
    json_data = json.load(f)
© www.soinside.com 2019 - 2024. All rights reserved.