【问题标题】:Python is throwing error when reading from a JSON file从 JSON 文件读取时 Python 抛出错误
【发布时间】:2019-11-29 09:52:55
【问题描述】:

我有一些 JSON 文件,内容如下:

{
  "name": "",
  "street": "",
  "street_number": 26,
  "district": "VILA MARESIA",
  "city": "Raposa",
  "state": "",
  "country": "BR",
  "latitude": ,
  "longitude": 
  }

现在加载这个文件会抛出如下错误:

    with open(r"C:\Users\dverma25\menus-folder\menus-folder-MA\rt.json",'r', encoding="utf8") as json_file:
            json_data = json.load(json_file)

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-93-8150dd6a3e1d> in <module>
      2         logger.info("Start processing the file {}".format(file))
      3 #         t = json_file.read()
----> 4         json_data = json.load(json_file)

C:\ProgramData\Anaconda3\lib\json\__init__.py in load(fp, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    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)
    297 
    298 

C:\ProgramData\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

C:\ProgramData\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):

C:\ProgramData\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 9 column 15 (char 153)

我知道这背后的原因是“纬度”字段的值丢失,既不是空字符串也不是 None(因为源 API 中的数据类型对于该字段是双精度的)。谁能建议一种打开文件并将其加载到 json maodule 中的方法。

PS:我也尝试打开文件并使用了 josn.dump(file_obj.read()) 但这有一个问题,即它也会在 dump() 中使用所有回车符。

【问题讨论】:

  • 您没有 json 文件,因为您发布的不是有效的 json。
  • 我知道这不是一个有效的 json,但我从中获取数据的应用程序就是以这种方式设计的。所以真的要找到解决它的方法。

标签: json python-3.x rest dictionary


【解决方案1】:

在您的特定情况下,您可以从文件中加载无效的 json 字符串,然后对无效条目使用粗略的 str.replace 将它们设置为 null。

import json

my_json = """{
  "name": "",
  "street": "",
  "street_number": 26,
  "district": "VILA MARESIA",
  "city": "Raposa",
  "state": "",
  "country": "BR",
  "latitude": ,
  "longitude": 
  }"""

my_json = my_json.replace(": ,", ": null,").replace(": \n", ": null\n")
print(json.loads(my_json))

输出

{'name': '', 'street': '', 'street_number': 26, 'district': 'VILA MARESIA', 'city': 'Raposa', 'state': '', 'country': 'BR', 'latitude': None, 'longitude': None}

【讨论】:

  • 感谢您的回答,但是对于存在任何字段(纬度或经度)的值的情况,这会引发错误,因为这些是数值,而不是字符串。我得到的错误:JSONDecodeError:期望用双引号括起来的属性名称:第 12 行第 3 列(字符 255)。
  • 什么意思?基于您的示例数据作为最小可重现示例,上述数据和替换工作并允许成功解析 json
  • 很遗憾,我忘记删除多余的逗号 (,)。很好用,谢谢!
【解决方案2】:

您的文件的 JSON 格式不正确。特别是这些行:

"latitude": ,
"longitude": 

它们看起来像没有值部分的字典的键值对。它们应该如下所示:

"latitude": "",
"longitude": ""

【讨论】:

  • 我知道,但我已经提到,在 PS 中,源 API 已将其定义为 double 类型。
猜你喜欢
  • 1970-01-01
  • 2020-10-11
  • 2019-04-27
  • 2018-12-14
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
相关资源
最近更新 更多