以下是使用Python遍历Foursquare API返回的JSON数据的示例代码:
import requests
import json
# 发送GET请求获取Foursquare API的JSON数据
url = 'https://api.foursquare.com/v2/venues/explore'
params = {
'client_id': 'YOUR_CLIENT_ID',
'client_secret': 'YOUR_CLIENT_SECRET',
'v': '20220101',
'll': '40.7128,-74.0060',
'query': 'restaurant'
}
response = requests.get(url, params=params)
data = response.json()
# 遍历JSON数据
for item in data['response']['groups'][0]['items']:
venue = item['venue']
name = venue['name']
location = venue['location']
address = location.get('address', '')
city = location.get('city', '')
state = location.get('state', '')
country = location.get('country', '')
print(f"Name: {name}")
print(f"Address: {address}")
print(f"City: {city}")
print(f"State: {state}")
print(f"Country: {country}")
print('---')
请注意,在使用此示例代码之前,您需要替换YOUR_CLIENT_ID
和YOUR_CLIENT_SECRET
为您自己的Foursquare API凭据。此示例代码将获取在纽约市附近的餐厅,并打印出每个餐厅的名称、地址、城市、州和国家信息。
此示例代码假设Foursquare API的响应JSON数据结构类似于以下示例:
{
"response": {
"groups": [
{
"items": [
{
"venue": {
"name": "Restaurant 1",
"location": {
"address": "123 Main St",
"city": "New York",
"state": "NY",
"country": "USA"
}
}
},
{
"venue": {
"name": "Restaurant 2",
"location": {
"address": "456 Elm St",
"city": "New York",
"state": "NY",
"country": "USA"
}
}
},
...
]
}
]
}
}
您可以根据实际的Foursquare API响应数据结构进行相应的修改和调整。
上一篇:遍历 JObject 嵌套数组