gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:07:09 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com