我正在和Pandas一起工作,我必须解析一个JSON文件,它来自朱庇特笔记本。以下是books.json的内容
[
{
"writer": "Mark Ross",
"nationality": "USA",
"books": [
{
"title": "XML Cookbook",
"price": 23.56
},
{
"title": "Python Fundamentals",
"price": 50.70
},
{
"title": "The NumPy library",
"price": 12.30
}
]
},
{
"writer": "Barbara Bracket",
"nationality": "UK",
"books": [
{
"title": "Java Enterprise",
"price": 28.60
},
{
"title": "HTML5",
"price": 31.35
},
{
"title": "Python for Dummies",
"price": 28.00
}
]
}
]当我通过朱庇特笔记本试试下面的代码时,
import json
file = open('./books.json', 'r')
text = file.read()
text = json.loads(text)上面的代码块的最后一行出现了错误
---------------------------------------------------------------------------
JSONDecodeError Traceback (most recent call last)
/tmp/ipykernel_5338/2028572637.py in <module>
----> 1 text = json.loads(text)
/usr/lib/python3.8/json/__init__.py in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
355 parse_int is None and parse_float is None and
356 parse_constant is None and object_pairs_hook is None and not kw):
--> 357 return _default_decoder.decode(s)
358 if cls is None:
359 cls = JSONDecoder
/usr/lib/python3.8/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):
/usr/lib/python3.8/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 1 column 1 (char 0)我试图读取该文件并将其重写到另一个JSON文件中,在本例中删除空格和制表符,但没有工作。
发布于 2022-04-26 14:15:06
它引发的最后一个错误意味着text是空的。
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
当text为空时,将返回此准确错误。
注意,您提供的JSON值通过在线JSON验证器,如果问题在JSON本身中,则会引发不同的错误。
尝试按以下方式加载json文件。
with open(filename) as infile:
data = json.load(infile)注意,我将名称从text更改为data,以避免对变量内容的混淆。
https://stackoverflow.com/questions/72015162
复制相似问题