【问题标题】:Storing API data in Json fromat以 Json 格式存储 API 数据
【发布时间】:2021-08-07 17:07:38
【问题描述】:

我有一个 API,其中所有位置 ID 及其各自的信息(如(地址、纬度、经度)都存在。但是,如果我想获取其他额外属性,例如位置名称、位置区域、位置访问权限,那么我需要在 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   
........................  
.......................



     

【问题讨论】:

    标签: python arrays json dataframe api


    【解决方案1】:

    这是您示例的简化版本,它查询返回 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)
    

    我建议使用Requests 库,因为它的api 比urllib 更简单,并且被python 社区广泛使用。这是Requests 库的相同示例。

    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)
    

    【讨论】:

    • 上面的代码创建了许多 json 文件。它为一个位置创建一个 json。我有超过 1000 个位置,所以它创建了大约 1000 个 json 文件。我需要像第一个 json conatins n 位置这样的输出第二个 json 包含另一个 n 位置等等..就像我提到的问题
    • 更新答案以返回包含 j 个项目的 i 个文件
    • 以上代码生成错误TypeError: Object of type Response is not JSON serializable
    • 是否可以从响应中仅获取位置 ID?
    • 当然。在我的示例中,response_data 是一本字典。而不是附加整个字典,您可以使用response.append({"id": response_data["location_id"]}) 附加字典,或者如果您只想要idsresponse.append(response_data["location_id"])。跨度>
    猜你喜欢
    • 2012-04-15
    • 2014-06-15
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多