我似乎已經用盡了互聯網搜索感覺很常見的事情,我需要一些幫助,請。
我正在使用 requests 庫進行 API 呼叫,每次呼叫回傳一個 JSON 回應 - 我將遍歷并進行多次呼叫。
我想將來自許多 API 呼叫的所有回應合并到一個 Python 資料結構中,然后將結果匯出到 CSV。
一個 API 回應如下所示:
{
"status": "1",
"msg": "Success",
"data": {
"id": "12345",
"PriceDetail": [
{
"item": "Apple",
"amount": "10",
"weight": "225",
"price": "92",
"bestbeforeendeate": "30/09/2023"
}
]
}
}
我的最終輸出應該是一個 CSV 檔案,在后續行中包含以下標題和資料:
| ID | 物品 | 數量 | 重量 | 價錢 | 最好的選擇 |
|---|---|---|---|---|---|
| 12345 | 蘋果 | 10 | 225 | 92 | 30/09/2023 |
| ..... | ..... | .. | ... | .. | ..... |
我已經考慮在字典中組合回應,命名為元組,資料框,并嘗試了從上述結構(如 dictwriter、csvwriter、normalize 等)匯出的各種選項。不過,我仍在努力使其作業。
我得到的最接近的是(我將結果保存到 JSON 檔案以停止訪問 API):
with open('item.json') as json_file:
data_set = json.load(json_file)
for data in data_set:
if data['msg'] == 'Success':
id = data['data']['id']
return_data[id] = data['data']['PriceDetail']
df = pd.json_normalize(data['data']['PriceDetail'])
print(df)
我無法將 ID 添加到資料框中
任何建議,將不勝感激。
謝謝,
uj5u.com熱心網友回復:
Pandas 有一個函式叫做json_normalize,它可以直接將字典轉換為資料幀。為了將 JSON 字串轉換為 JSON 字串,dict您只需使用該json庫即可。我發現的好來源是這個`.
import json
import pandas as pd
# Test string, assuming it is from API
test_string = """{
"status": "1",
"msg": "Success",
"data": {
"id": "12345",
"PriceDetail": [
{
"item": "Apple",
"amount": "10",
"weight": "225",
"price": "92",
"bestbeforeendeate": "30/09/2023"
}
]
}
}"""
# Function converts the api result to the dataframe and appends it to df
def add_new_entry_to_dataframe(df, api_result_string):
input_parsed = json.loads(api_result_string)
df_with_new_data = pd.json_normalize(input_parsed['data']['PriceDetail'])
df = df.append(df_with_new_data)
return df
# The dataframe you want to store everything
df = pd.DataFrame()
## Loop where you fetch new data
for i in range(10):
newly_fetched_result = test_string
df = add_new_entry_to_dataframe(df, newly_fetched_result)
df = df.reset_index()
# Save as .csv
df.to_csv('output.csv')
print(df)
上面代碼的輸出:
item amount weight price bestbeforeendeate
0 Apple 10 225 92 30/09/2023
0 Apple 10 225 92 30/09/2023
0 Apple 10 225 92 30/09/2023
0 Apple 10 225 92 30/09/2023
0 Apple 10 225 92 30/09/2023
0 Apple 10 225 92 30/09/2023
0 Apple 10 225 92 30/09/2023
0 Apple 10 225 92 30/09/2023
0 Apple 10 225 92 30/09/2023
0 Apple 10 225 92 30/09/2023
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/358446.html
