Skip to main content
 首页 » 编程设计

Python 3之将来自多个 API 请求的 JSON 解析为列表并输出到文件

2025年05月04日14tintown

我该如何...

1) 在 Python 3 中从 API 查询中解析 JSON 对象

2) 将多个请求解析成一个列表,并

3) 将列表输出成JSON文件

请您参考如下方法:

我更喜欢使用 requests适用于所有 API 编程。这是一个单行代码,它获取多个 API 调用的结果,将它们放在一个列表中,并将该列表写入一个 JSON 文件:

json.dump([requests.get(url).json() for url in URLs], fp) 

完整的测试程序如下:

import requests 
import json 
 
URLs = [ 
    # Some URLs that return JSON objects 
    'http://httpbin.org/ip', 
    'http://httpbin.org/user-agent', 
    'http://httpbin.org/headers' 
] 
 
with open('result.json', 'w') as fp: 
    json.dump([requests.get(url).json() for url in URLs], fp, indent=2) 

如果您出于某种原因对 requests 过敏,这里是等效的 Python3 代码,仅使用标准库。

from urllib.request import urlopen 
import json 
 
URLs = [ 
    # Some URLs that return JSON objects 
    'http://httpbin.org/ip', 
    'http://httpbin.org/user-agent', 
    'http://httpbin.org/headers' 
] 
 
json_list = [] 
for url in URLs: 
    resp = urlopen(url) 
    resp = resp.read().decode(resp.headers.get_content_charset() or 'ascii') 
    json_list.append(json.loads(resp)) 
with open('result.json', 'w') as fp: 
    json.dump(json_list, fp, indent=2)