简体   繁体   English

使用 Python SDK 将 Amazon PA API 响应保存到 JSON 文件

[英]Saving Amazon PA API response to JSON file using Python SDK

I am calling the Amazon Product Advertising API in Python to get data for certain products: https://webservices.amazon.com/paapi5/documentation/quick-start/using-sdk.html .我在 Python 中调用亚马逊产品广告 API 以获取某些产品的数据: https : //webservices.amazon.com/paapi5/documentation/quick-start/using-sdk.html

I import the API with:我使用以下命令导入 API:

from paapi5_python_sdk.api.default_api import DefaultApi
from paapi5_python_sdk.models.search_items_request import SearchItemsRequest
from paapi5_python_sdk.models.search_items_resource import SearchItemsResource

I call the API using this:我使用这个调用 API:

response = default_api.search_items(search_items_request)

Then I try to write the response object to a file using basic code:然后我尝试使用基本代码将响应对象写入文件:

with open('paapi_response.json', 'w') as outfile:
   outfile.write(response)

But I get the following error:但我收到以下错误:

TypeError : write() argument must be str, not SearchItemsResponse TypeError : write() 参数必须是 str,而不是 SearchItemsResponse

I don't want to convert it to string because I want to keep the exact response of the file.我不想将其转换为字符串,因为我想保留文件的确切响应。 Is there any way to print the response object to a file just as it is?有没有办法将响应对象按原样打印到文件中?

The SearchItemsResponse has a to_dict method which recursively converts it to a nested dictionary/list data structure. SearchItemsResponse有一个to_dict方法,它递归地将其转换为嵌套的字典/列表数据结构。 1 1

This you can write to a file as JSON as shown in How do I write JSON data to a file?您可以将其作为 JSON 写入文件,如如何将 JSON 数据写入文件中所示? :

import json

# ...

with open('paapi_response.json', 'w') as outfile:
    json.dump(response.to_dict(), outfile)

1 Reference: lines 112 to 137 in the file paapi5-python-sdk-example/paapi5_python_sdk/models/search_items_response.py from the Python SDK zip file downloaded from the page you have linked. 1参考:从您链接的页面下载的Python SDK zip 文件中的文件paapi5-python-sdk-example/paapi5_python_sdk/models/search_items_response.py中的第 112 至 137 行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM