
本教程旨在解决接收到由多个独立json对象直接拼接而成,而非封装在数组或以逗号分隔的非标准json响应数据。我们将介绍一种基于行检测的python方法,通过识别相邻的`}`和`{`字符序列来精确分割并解析每个独立的json对象,从而有效处理此类特殊数据格式。
在数据交换中,JSON(JavaScript Object Notation)因其轻量级和易于解析的特性而广受欢迎。通常,当我们需要传输多个JSON对象时,它们会被封装在一个JSON数组中,例如 [{...}, {...}],或者以逗号分隔。然而,在某些特定场景下,我们可能会遇到一种非标准的JSON响应格式,即多个独立的JSON对象直接拼接在一起,既没有外部的数组方括号,也没有对象之间的逗号分隔符。这种格式 {...}{...} 无法直接使用标准的 json.loads() 方法进行解析,因为它不构成一个合法的JSON文档。
标准的JSON规范要求一个JSON文档要么是一个对象,要么是一个数组。当服务器返回多个JSON对象时,它们通常会像这样组织:
[
{
"id": 1,
"name": "Object One"
},
{
"id": 2,
"name": "Object Two"
}
]然而,本教程所讨论的场景是接收到以下形式的数据:
{
"self": "https://example1.com",
"key": "keyOne",
"name": "nameOne",
"emailAddress": "mailOne",
"avatarUrls": {
"48x48": "https://test.com/secure/useravatar?avatarId=1",
"24x24": "https://test.com/secure/useravatar?size=small&avatarId=1",
"16x16": "https://test.com/secure/useravatar?size=xsmall&avatarId=1",
"32x32": "https://test.com/secure/useravatar?size=medium&avatarId=1"
},
"displayName": "displayNameOne",
"active": true,
"timeZone": "Europe",
"locale": "en_UK"
}
{
"self": "https://example2.com",
"key": "keyTwo",
"name": "nameTwo",
"emailAddress": "mailTwo",
"avatarUrls": {
"48x48": "https://test.com/secure/useravatar?avatarId=2",
"24x24": "https://test.com/secure/useravatar?size=small&avatarId=2",
"16x16": "https://test.com/secure/useravatar?size=xsmall&avatarId=2",
"32x32": "https://test.com/secure/useravatar?size=medium&avatarId=2"
},
"displayName": "displayNameTwo",
"active": false,
"timeZone": "Europe",
"locale": "en_US"
}这种格式在Python中直接使用 json.loads() 会导致 json.JSONDecodeError,因为它被视为一个包含多个根级别元素的无效JSON字符串。
立即学习“Python免费学习笔记(深入)”;
要成功解析这种非标准格式,我们需要一种方法来识别每个独立JSON对象的边界。观察上述数据结构,可以发现一个关键模式:一个JSON对象的结束标记 } 紧接着下一行就是下一个JSON对象的开始标记 {。我们可以利用这个特征来手动分割整个响应字符串。
核心思路如下:
以下是使用Python实现此解析策略的详细步骤和代码:
首先,准备我们的非标准JSON数据:
data = '''
{
"self": "https://example1.com",
"key": "keyOne",
"name": "nameOne",
"emailAddress": "mailOne",
"avatarUrls": {
"48x48": "https://test.com/secure/useravatar?avatarId=1",
"24x24": "https://test.com/secure/useravatar?size=small&avatarId=1",
"16x16": "https://test.com/secure/useravatar?size=xsmall&avatarId=1",
"32x32": "https://test.com/secure/useravatar?size=medium&avatarId=1"
},
"displayName": "displayNameOne",
"active": true,
"timeZone": "Europe",
"locale": "en_UK"
}
{
"self": "https://example2.com",
"key": "keyTwo",
"name": "nameTwo",
"emailAddress": "mailTwo",
"avatarUrls": {
"48x48": "https://test.com/secure/useravatar?avatarId=2",
"24x24": "https://test.com/secure/useravatar?size=small&avatarId=2",
"16x16": "https://test.com/secure/useravatar?size=xsmall&avatarId=2",
"32x32": "https://test.com/secure/useravatar?size=medium&avatarId=2"
},
"displayName": "displayNameTwo",
"active": false,
"timeZone": "Europe",
"locale": "en_US"
}
'''接下来是解析代码:
享有盛誉的PHP高级教程,Zend Framework核心开发人员力作,深入设计模式、PHP标准库和JSON 。 今天,PHP已经是无可争议的Web开发主流语言。PHP 5以后,它的面向对象特性也足以与Java和C#相抗衡。然而,讲述PHP高级特性的资料一直缺乏,大大影响了PHP语言的深入应用。 本书填补了这一空白。它专门针对有一定经验的PHP程序员,详细讲解了对他们最为重要的主题
455
from json import loads, dumps
jlist = [] # 用于存储解析后的JSON对象
k = 0 # 标记当前JSON对象开始的行索引
# 将原始数据按行分割
lines = data.splitlines()
# 遍历所有行,查找对象边界
for i, line in enumerate(lines):
# 检查当前行是否为 '{' 且前一行是否为 '}'
# i > 0 确保不是第一行,避免索引越界
if i > 0 and line.strip() == "{" and lines[i-1].strip() == "}":
# 找到了一个对象边界,将从 k 到 i 的行拼接成一个JSON字符串并解析
json_str_segment = "".join(lines[k:i])
jlist.append(loads(json_str_segment))
k = i # 更新 k 为新对象的起始行
# 处理最后一个JSON对象
# 循环结束后,从 k 到末尾的行构成了最后一个JSON对象
json_str_segment = "".join(lines[k:])
jlist.append(loads(json_str_segment))
# 打印解析后的每个JSON对象以验证
for j_obj in jlist:
print(dumps(j_obj, indent=2, ensure_ascii=False))
print("-" * 30) # 分隔符,便于查看代码解释:
执行上述代码后,你将看到每个独立的JSON对象都被正确解析并格式化打印出来:
{
"self": "https://example1.com",
"key": "keyOne",
"name": "nameOne",
"emailAddress": "mailOne",
"avatarUrls": {
"48x48": "https://test.com/secure/useravatar?avatarId=1",
"24x24": "https://test.com/secure/useravatar?size=small&avatarId=1",
"16x16": "https://test.com/secure/useravatar?size=xsmall&avatarId=1",
"32x32": "https://test.com/secure/useravatar?size=medium&avatarId=1"
},
"displayName": "displayNameOne",
"active": true,
"timeZone": "Europe",
"locale": "en_UK"
}
------------------------------
{
"self": "https://example2.com",
"key": "keyTwo",
"name": "nameTwo",
"emailAddress": "mailTwo",
"avatarUrls": {
"48x48": "https://test.com/secure/useravatar?avatarId=2",
"24x24": "https://test.com/secure/useravatar?size=small&avatarId=2",
"16x16": "https://test.com/secure/useravatar?size=xsmall&avatarId=2",
"32x32": "https://test.com/secure/useravatar?size=medium&avatarId=2"
},
"displayName": "displayNameTwo",
"active": false,
"timeZone": "Europe",
"locale": "en_US"
}
------------------------------格式依赖性: 此方法高度依赖于 } 和 { 字符在独立行上且彼此相邻的特定模式。如果JSON对象内部的字符串值恰好包含 } 或 { 并在行尾/行首,或者 } 和 { 不在单独的行上(例如,{"a":1}{"b":2} 这种单行拼接),此方法可能需要调整甚至失效。
空白字符: 代码中使用了 .strip() 来处理行首尾的空白,这增强了对格式变化的容错性。但如果 } 或 { 周围有其他非空白字符,则此方法将不适用。
错误处理: json.loads() 在遇到任何无效的JSON片段时都会抛出 json.JSONDecodeError 异常。在生产环境中,强烈建议将 loads() 调用封装在 try-except 块中,以便优雅地处理可能出现的解析错误,例如:
try:
jlist.append(loads(json_str_segment))
except json.JSONDecodeError as e:
print(f"Error decoding JSON segment: {e}")
print(f"Problematic segment: {json_str_segment}")
# 可以选择跳过此段或进行其他错误处理性能: 对于非常大的文件,按行读取和拼接字符串可能会有一定的性能开销。但对于大多数常见的JSON响应大小,这种方法是高效且可接受的。
替代方案: 如果数据格式更加复杂或不规则,例如 }{ 不总是出现在独立行上,或者对象之间有其他非JSON内容,那么可能需要更强大的文本处理工具,如正则表达式 (re 模块) 来匹配和提取每个JSON对象。
当面对非标准的多个JSON对象直接拼接的响应数据时,直接使用 json.loads() 是行不通的。通过分析其独特的结构特征,即 } 紧接着 { 的行模式,我们可以设计一个基于行检测的Python解析策略。此方法能够有效地将整个响应字符串分割成独立的、可解析的JSON片段,从而成功提取出所有数据。在实际应用中,务必考虑数据格式的稳定性和可能出现的异常情况,并添加相应的错误处理机制,以确保程序的健壮性。理解并适应各种数据格式是处理外部数据时的关键技能。
以上就是解析非标准多对象JSON响应的Python教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号