API(应用程序编程接口)是一种允许不同软件应用程序之间进行交互的协议。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。
假设我们有一个API返回如下JSON数据:
{
"name": "John Doe",
"age": 30,
"email": "john.doe@example.com",
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
}
}
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data.name); // 输出: John Doe
console.log(data.age); // 输出: 30
console.log(data.email); // 输出: john.doe@example.com
console.log(data.address.city); // 输出: Anytown
})
.catch(error => console.error('Error:', error));
import requests
response = requests.get('https://api.example.com/data')
data = response.json()
print(data['name']) # 输出: John Doe
print(data['age']) # 输出: 30
print(data['email']) # 输出: john.doe@example.com
print(data['address']['city']) # 输出: Anytown
原因:可能是由于JSON格式不正确或数据损坏。
解决方法:
try:
data = response.json()
except ValueError as e:
print(f"JSON解析错误: {e}")
原因:可能是由于网络问题或API服务器不可达。
解决方法:
try-except
块捕获网络请求异常。try:
response = requests.get('https://api.example.com/data', timeout=5)
response.raise_for_status() # 如果响应状态码不是200,会抛出HTTPError异常
except requests.exceptions.RequestException as e:
print(f"网络请求失败: {e}")
通过以上方法,可以有效处理从API获取JSON数据时可能遇到的常见问题。
没有搜到相关的文章