Skip to main content
 首页 » 编程设计

python之如何读取两个串联的 JSON 文件

2025年05月04日13sky-heaven

我有以下由两个串联的 JSON 字符串组成的文件:

{ 
  "hello": 2, 
  "world": 3 
}{ 
  "something": 5, 
  "else": 6 
} 

它们都是正确的(它们比那更复杂,但总是两个 JSON 字典一个接一个)。

因为我可以预测第一个格式(接近我上面的示例),我将使用正则表达式解析文件并最终将它们分开(我只需要第二个 JSON):

{[\s\S]*?}([.\n]*?) 

虽然这个解决方案有效,但我想确保没有更通用的方法来解决这个问题。

请您参考如下方法:

raw_decode 将解析一个字符串并返回它的对象加上对象序列化结束的索引。只要文档合理地适合内存,您就可以蚕食该字符串。

>>> text="""{ 
...   "hello": 2, 
...   "world": 3 
... }{ 
...   "something": 5, 
...   "else": 6 
... } 
...  
... """ 
 
>>> import json 
>>> decoder = json.JSONDecoder() 
>>> text = text.lstrip() # decode hates leading whitespace 
>>> while text: 
...     obj, index = decoder.raw_decode(text) 
...     text = text[index:].lstrip() 
...     print(obj) 
...  
{'world': 3, 'hello': 2} 
{'else': 6, 'something': 5}