【问题标题】:Getting decode Error when reading JSON file读取 JSON 文件时出现解码错误
【发布时间】:2020-11-20 18:15:58
【问题描述】:

我正在尝试读取 JSON 文件,但它给出了如下错误

数据参考: https://github.com/ankitgoel1602/data-science/blob/master/json-data/level_1.json https://github.com/ankitgoel1602/data-science/blob/master/json-data/multiple_levels.json

代码

with open("multiple_levels.json", 'r') as j:
 contents = json.loads(j.read())

错误:

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-14-0fce326c8851> in <module>
      1 with open("multiple_levels.json", 'r') as j:
----> 2      contents = json.loads(j.read())

~\AppData\Local\Continuum\anaconda3\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    346             parse_int is None and parse_float is None and
    347             parse_constant is None and object_pairs_hook is None and not kw):
--> 348         return _default_decoder.decode(s)
    349     if cls is None:
    350         cls = JSONDecoder

~\AppData\Local\Continuum\anaconda3\lib\json\decoder.py in decode(self, s, _w)
    335 
    336         """
--> 337         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338         end = _w(s, end).end()
    339         if end != len(s):

~\AppData\Local\Continuum\anaconda3\lib\json\decoder.py in raw_decode(self, s, idx)
    353             obj, end = self.scan_once(s, idx)
    354         except StopIteration as err:
--> 355             raise JSONDecodeError("Expecting value", s, err.value) from None
    356         return obj, end

JSONDecodeError: Expecting value: line 7 column 1 (char 6)

【问题讨论】:

  • 我刚刚检查了 Python 3.7,您的代码运行良好。

标签: json python-3.x


【解决方案1】:

问题是当您从 github 下载文件而不是您的代码时。 github中的文件内容不是您简单地“将链接另存为”时看到的内容 作为一种解决方案,您可以前往 github 存储库并以 zip 格式下载(见附件)

或者由于文件 json-data/level-1.json 很小,只需复制/粘贴并保存到您的文本编辑器中。

这是从 github 正确下载文件后的结果。

这是执行“将链接另存为”的文件内容。

查看第 7 行,您的代码在哪里抱怨。

【讨论】:

    【解决方案2】:

    如果您使用“原始内容” URL,您可以直接从网络加载 json:

    import json
    import urllib.request
    
    url = "https://raw.githubusercontent.com/ankitgoel1602/data-science/master/json-data/multiple_levels.json"
    with urllib.request.urlopen(url) as r:
        data = json.loads(r.read().decode())
    
    print(data)
    [{'Scaler': 'Standard', 'family_min_samples_percentage': 5, 'original_number_of_clusters': 4, 
      'Results': [{'eps_value': 0.1, 'min_samples': 5, 'number_of_clusters': 9, 'number_of_noise_samples': 72, 
                   'scores': {'adjusted_rand_index': 0.0012946494377947854, 
                              'adjusted_mutual_info_score': 0.008962599716725805, 'homogeneity_score': ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2019-01-23
      • 2020-10-11
      • 1970-01-01
      • 2018-12-14
      • 2016-02-07
      • 1970-01-01
      相关资源
      最近更新 更多