将API数据存储在Json from at中



我有一个API,其中包含所有位置id和它们各自的信息,如(地址、Lat、long(。但如果我想获取其他额外的属性,如位置名称、位置区域、位置访问,那么我需要在API中一个接一个地给出位置id作为参数,以获取它们各自的额外属性。

我已经写了下面的代码。但下面的代码的问题是数据来自控制台,我不知道如何将这些信息保存在json中,然后将其转换为文本文件。

ids=location_id_df["id"] #stored location id in dataframe 
authorization =”####################### "
print("started")  
def test_api(url, authorization, rawfile,ids):
for i in range(0,1000,50):
for j in ids:
#print(j)
try:
request = urllib.request.Request('https:….. /locations/{}'.format(j)+"? 
            
offset="+str(i),headers={'authorization':authorization})


response = urllib.request.urlopen(request).read()
print(response)



except HTTPError as e:
print(e)
sys.exit(0)

with open(rawfile + "_offset_" + str(i) + ".json", "wb") as json_download:
json_download.write(response)
test_api(url, authorization, rawfile,ids)  

我需要在类似的json中完成响应

5182021_offset_0.json #contains some location id's with extra attribute data                                         
5182021_offset_50.json #contains some location id's with extra attribute data   
5182021_offset_100.json  #contains some location id's with extra attribute data   
........................  
.......................


这里是您的示例的简化版本,它查询一个返回json的api,并将每个结果保存到一个文件中。

import urllib.request
import json
for i in range(2):
responses = []
for j in range(3):
request = urllib.request.Request("https://www.boredapi.com/api/activity/")
response = urllib.request.urlopen(request)
if response.status == 200:
try:
response_bytes = response.read()
finally:
response.close()
response_string = response_bytes.decode("utf8")
response_data = json.loads(response_string)
responses.append(response_data)
file_name = "data-{}.json".format(i)
with open(file_name, "w") as f:
json.dump(responses, f)

我建议使用请求库,因为它的api往往比urllib更简单,并且被python社区广泛使用。下面是与请求库相同的示例。

import requests
import json

for i in range(2):
responses = []
for j in range(3):
response = requests.get("https://www.boredapi.com/api/activity/")
if response.status_code == 200:
response_data = response.json()
responses.append(response_data)
file_name = "data-{}.json".format(i)
with open(file_name, "w") as f:
json.dump(responses, f)

相关内容

最新更新