Skip to main content
 首页 » 编程设计

python之如何在 Python 中读取包含多个 JSON 对象的 JSON 文件

2024年10月24日7lhb25

所以这是在 python 中读取 JSON 文件的标准方法

import json 
from pprint import pprint 
 
with open('ig001.json') as data_file:     
    data = json.load(data_file) 
 
pprint(data) 

但是,我要读取的 JSON 文件中有多个 JSON 对象。所以它看起来像:

[{},{}.... ]

[{},{}.... ]

这表示 2 个 JSON 对象,在每个 {} 中的每个对象中,有一堆键值对。

因此,当我尝试使用上面的标准读取代码读取此内容时,出现错误:

Traceback (most recent call last): File "jsonformatter.py", line 5, in data = json.load(data_file) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py", line 290, in load **kw) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py", line 338, in loads return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 369, in decode raise ValueError(errmsg("Extra data", s, end, len(s))) ValueError: Extra data: line 3889 column 2 - line 719307 column 2 (char 164691 - 30776399)

第 3889 行是第一个 JSON 对象结束和下一个对象开始的地方,该行本身看起来像“][”。

任何关于如何解决此问题的想法将不胜感激,谢谢!

请您参考如下方法:

如果没有链接您的 JSON 文件,我将不得不做出一些假设:

  1. 顶级 json 数组不是每个都在自己的行上(因为第一个解析错误在第 3889 行),所以我们不能轻易
  2. 这是文件中唯一存在的无效 JSON 类型。

解决这个问题:

# 1. replace instances of `][` with `]<SPLIT>[` 
# (`<SPLIT>` needs to be something that is not present anywhere in the file to begin with) 
 
raw_data = data_file.read()  # we're going to need the entire file in memory 
tweaked_data = raw_data.replace('][', ']<SPLIT>[') 
 
# 2. split the string into an array of strings, using the chosen split indicator 
 
split_data = tweaked_data.split('<SPLIT>') 
 
# 3. load each string individually 
 
parsed_data = [json.loads(bit_of_data) for bit_of_data in split_data] 

(请原谅可怕的变量名)