You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python解析无数组包裹的多JSON对象API响应

问题描述

API返回的响应包含多个独立的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"
}

尝试过遍历响应、用方括号包裹整个响应等方法,均无法成功解析,求Python下的解决办法。

Python 解决方法

方法一:使用 json.JSONDecoder 的 raw_decode 方法

json.JSONDecoder 的 raw_decode 方法可以从字符串任意位置开始解析JSON对象,同时返回解析后的对象和解析结束的索引。循环调用该方法即可处理完所有独立JSON对象。

示例代码:

import json

def parse_multiple_json(raw_data):
    decoder = json.JSONDecoder()
    pos = 0
    results = []
    while pos < len(raw_data):
        try:
            obj, pos = decoder.raw_decode(raw_data, pos)
            results.append(obj)
            # 跳过解析后的空白字符
            while pos < len(raw_data) and raw_data[pos].isspace():
                pos += 1
        except json.JSONDecodeError:
            raise
    return results

# 假设response_text是API返回的原始字符串
response_text = """{
"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"
}"""

parsed_data = parse_multiple_json(response_text)
for item in parsed_data:
    print(item["displayName"])

方法二:手动分割并处理嵌套结构

通过计数大括号的方式分割独立JSON对象,同时处理嵌套的{}(比如示例中的avatarUrls字段),避免误分割。

示例代码:

import json

def split_multiple_json(raw_data):
    brace_count = 0
    start_pos = 0
    results = []
    for i, char in enumerate(raw_data):
        if char == '{':
            brace_count += 1
            if brace_count == 1:
                start_pos = i
        elif char == '}':
            brace_count -= 1
            if brace_count == 0:
                json_str = raw_data[start_pos:i+1].strip()
                if json_str:
                    results.append(json.loads(json_str))
    return results

# 使用上面的response_text测试
parsed_data = split_multiple_json(response_text)
for item in parsed_data:
    print(item["key"])

内容的提问来源于stack exchange,提问作者Jack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 14:47:32