以下是一个示例代码,展示如何遍历来自API的JSON格式的哈希数组。
import requests
# 发送GET请求获取API数据
response = requests.get('https://api.example.com/data')
data = response.json()
# 遍历哈希数组
for item in data:
# 输出每个哈希的键和值
for key, value in item.items():
print(f"{key}: {value}")
print('-' * 20) # 分隔每个哈希的输出
上述示例中,首先发送GET请求来获取API数据,并将其转换为JSON格式的哈希数组。然后,使用嵌套的循环遍历哈希数组中的每个哈希。在内部循环中,输出每个哈希的键和值。为了使输出更加清晰,使用了分隔线将每个哈希的输出分隔开。
上一篇:遍历扩展类列表并动态创建对象