背景 -
我正在撰寫一些代碼,這些代碼將接受 API 回應,將其寫入檔案,并將其保存在 Pandas DataFrame 中,并最終執行一些資料 QC。
問題 -
我有一個def response_writer():函式,它從另一個函式 ( def api_call():) 獲取api 呼叫的回應并使用json.dumps. 我對我的代碼進行了一些未記錄的更改,并注意到我的代碼用于將其另存api_response為 .json 檔案,但是由于對我的代碼進行了更改,“api_response”現在保存在“無擴展名”檔案中,盡管它似乎是JSON,當我打開檔案時看起來與更改前的檔案有所不同...
檔案 -
截圖 #1。在未記錄的代碼更改之前,我的 JSON 資料如何保存和查看 -

截圖#2。我的 JSON 代碼現在看起來如何,做了一些未記錄的更改 -

當前代碼 -
這些是我的功能,遵循未記錄的更改 -
一種。呼叫 api 的函式,并用于json.load()將回應保存在名為 的變數中api_response。
def api_call():
url_list = url_constructor()
for url in url_list:
response = requests.get(url_list[0], auth = HTTPBasicAuth(key, secret), headers={"My-Firm":"543"})
api_response = json.loads(response.text)
return api_response
灣 應該將api_response.JSON 檔案保存的函式。但是,雖然檔案中出現了 JSON,但它的結構與未記錄更改之前的結構不同(參見data.json上面的第二個螢屏截圖)。
def response_writer():
api_response = api_call()
timestr = datetime.datetime.now().strftime("%Y-%m-%d-%H:%M")
filename = 'api_response_' timestr
with open(filename, 'w', encoding='utf-8') as output_data:
json.dump(api_response, output_data)
print("--------------------------------------------\n", "API RESPONSE SAVED:", filename, "\n--------------------------------------------")
response_writer()
問題 -將api_response每個螢屏截圖 #1 與螢屏截圖 #2 寫入檔案有什么好處嗎?
最終,目標是使api_response保存到 Pandas DataFrame 盡可能容易。
uj5u.com熱心網友回復:
添加檔案擴展名可能會修復它:
def response_writer():
api_response = api_call()
timestr = datetime.datetime.now().strftime("%Y-%m-%d-%H:%M")
filename = 'api_response_' timestr '.json'
with open(filename, 'w', encoding='utf-8') as output_data:
json.dump(api_response, output_data)
print("--------------------------------------------\n", "API RESPONSE SAVED:", filename, "\n--------------------------------------------")
response_writer()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/373524.html
下一篇:從Json檔案加載資料
