gpt4 book ai didi

Python 使用 Django 将 python-amazon-simple-product-api 结果转换为 json

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:38 24 4
gpt4 key购买 nike

我正在Python Django 和rest 框架中编写一个API。我正在使用名为 python-amazon-simple-product-api 的 python 软件包来访问亚马逊广告 API。我正在尝试将结果输入到其余框架中,并将结果作为 JSON 返回。这是到目前为止我的代码。

class AmazonProductsViewSet(viewsets.ViewSet):
def list(self, request, format=None):
products = amazon.search(Brand="Microsoft", SearchIndex="Software",
ResponseGroup="Images,ItemAttributes,Accessories,Reviews,VariationSummary,Variations")
products = list(products)

使用此代码我收到以下错误;

TypeError: Object of type 'AmazonProduct' is not JSON serializable

所以我试图找到一种使 AmazonProduct 对象可序列化的方法或更好的解决方案。

最佳答案

不可 JSON 序列化意味着您的响应是一个对象,而不是可以通过网络发送的原始数据。

您需要为该模型编写一个序列化器。像这样的事情:

class AmazonProductSerializer(serializers.Serializer):
color = serializers.CharField()
title = serializers.CharField()

并像这样使用它:

products = amazon.search(Brand="Microsoft", SearchIndex="Software", ResponseGroup="Images,ItemAttributes,Accessories,Reviews,VariationSummary,Variations")

data = AmazonProductSerializer(products, many=True).data
return Response(data, status=status.HTTP_200_OK)

希望对你有帮助!

关于Python 使用 Django 将 python-amazon-simple-product-api 结果转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46635516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com