如何解析包含多个 JSON 对象的 JSON 响应

问题描述 投票:0回答:1

如何解析包含多个对象的 JSON 响应 参考上面的链接,我得到了多个 JSON 对象作为响应,但与上面链接中的响应(接收多个 JSON 的单个数组)不同,我得到了多个 JSON,两个 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"
}

我尝试循环处理 REST API 响应,考虑将响应括在方括号内,但都失败了。

使用多个 json 对象解析响应 我检查了上面的链接,但这里也检查了,但他们在单行中有一个 JSON 元素,而我的情况并非如此。如何使用 Python 完成任务请帮忙。

python json rest
1个回答
0
投票

你可以使用for循环来一一获取它们,这里是一个例子

response_data = ...
json_objects = response_data.strip().split('\n')

parsed_objects = []

for json_str in json_objects:
    parsed_object = json.loads(json_str)
    parsed_objects.append(parsed_object)
© www.soinside.com 2019 - 2024. All rights reserved.