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

soo*_*kie 1 python api json python-3.x

我如何能...

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

2)将多个请求解析为列表,并且

3)将列表输出到JSON文件中

Rob*_*obᵩ 6

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

json.dump([requests.get(url).json() for url in URLs], fp)
Run Code Online (Sandbox Code Playgroud)

这是一个完整的测试程序:

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)
Run Code Online (Sandbox Code Playgroud)

如果您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)
Run Code Online (Sandbox Code Playgroud)