json - Python 在读取 JSON 文件时抛出错误

标签 json python-3.x rest dictionary

我有一些包含以下内容的 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)

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

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

最佳答案

在您的特定情况下,您可以从文件加载无效的 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}

关于json - Python 在读取 JSON 文件时抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59102470/

相关文章:

arrays - 在 Karate 框架上访问具有随机或未知名称的嵌套 JSON 对象

python - 错误<0x7f6f60c6b8c0处<__main__.Node实例的绑定(bind)方法Node.getCpuPowerUsage>>

python - pycharm 中的“预期语句结束”

rest - 登录和注销操作应在 "RESTful"设置中使用哪种 HTTP 方法

javascript - Angular 休息 web2py

php - 如何将基本 HTTP 身份验证的凭据存储到服务器端的数据库中?

c# - 如何插入json文件而不删除以前的数据?

javascript - 如何使用不同的数据将数据多次解析到嵌套 View 中

javascript - Handlebars 选择框填充

python - DictCursor 与 RealDictCursor