使用 Python 的 GET 请求后解析并打印 JSON 结果

Parsing and printing JSON result after GET request using Python

在 Python 上的 GET 请求后,我尝试明确 json 结果:

import requests
import json

r = requests.get("https://smspva.com/api/rent.php?method=getcountries")

parsed = json.loads(r.text)

print(parsed)

我得到了这样的结果:

{'status': 1, 'data': [{'name': 'Russian Federation', 'code': 'RU'}, {'name': 'Ukraine', 'code': 'UA'}, {'name': 'Germany', 'code': 'DE'}, {'name': 'Czech Republic', 'code': 'CZ'}, {'name': 'United Kingdom', 'code': 'UK'}, {'name': 'Sweden', 'code': 'SE'}, {'name': 'Spain', 'code': 'ES'}, {'name': 'Portugal', 'code': 'PT'}, {'name': 'Netherlands', 'code': 'NL'}, {'name': 'Lithuania ', 'code': 'LT'}, {'name': 'Latvia', 'code': 'LV'}, {'name': 'Ireland', 'code': 'IE'}, {'name': 'Estonia', 'code': 'EE'}, {'name': 'United States', 'code': 'US'}]}

我怎样才能得到像这样的东西:

名称:俄罗斯联邦 代码 : RU

姓名:乌克兰 代码 : Ua

等等等等

感谢您的帮助!

您可以使用 Response.json()。然后遍历 data key:

import requests

resp = requests.get("https://smspva.com/api/rent.php?method=getcountries")
data = resp.json()
for country in data.get('data', []):
    print(f"Name:{country.get('name')} Code:{country.get('code')}")