在Python中解析JSON时出错(Jupyter Notebook)



我正在使用Pandas,我必须从Jupyter Notebook中解析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
}
    ]
}
]

当我通过Jupyter Notebook尝试下面的代码时,

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文件,在这种情况下剥离空格和制表符,但它没有工作。

它抛出的最后一个错误意味着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,以避免对变量的内容产生混淆。

最新更新