[英]Saving Amazon PA API response to JSON file using Python SDK
[英]Saving API response as a true .JSON file
背景 -
我正在编写一些代码,它将获取 API 响应,将其写入文件,并将其保存在 pandas DataFrame 中,并最终执行一些数据 QC。
问题 -
I have a def response_writer():
function, which takes the response of an api call from another function ( def api_call():
) and saves it using json.dumps
. 我对我的代码进行了一些未记录的更改,并注意到我的代码用于将api_response
保存为 .json 文件,但是由于对我的代码进行了更改,“api_response”现在保存在“无扩展名”文件中,虽然看起来是 JSON,当我打开文件时看起来不同,到预更改文件...
文件 -
截图#1 。 在未记录的代码更改之前,我的 JSON 数据如何保存和查看 -
截图#2。 我的 JSON 代码现在看起来如何,进行了一些未记录的更改 -
当前代码 -
在未记录的更改之后,这些是我的功能-
一个。 Function 调用 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
湾。 Function 应该将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()
问题 -每个屏幕截图 #1 和屏幕截图 #2 将api_response
写入文件有什么好处吗?
最终,目标是使api_response
尽可能容易地保存到 pandas DataFrame 中。
添加文件扩展名可能会修复它:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.