Python使用Django将Python amazon简单产品api结果转换为json

Python使用Django将Python amazon简单产品api结果转换为json,python,django,amazon-web-services,django-rest-framework,Python,Django,Amazon Web Services,Django Rest Framework,我正在用Python Django和rest框架编写一个API。我正在使用一个名为python amazon simple product api的python包来访问amazon广告api。我正在尝试将结果输入rest框架,并以JSON的形式返回结果。到目前为止,这是我的代码 class AmazonProductsViewSet(viewsets.ViewSet): def list(self, request, format=None): products = am

我正在用Python Django和rest框架编写一个API。我正在使用一个名为
python amazon simple product api
的python包来访问amazon广告api。我正在尝试将结果输入rest框架,并以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对象可序列化的方法或更好的解决方案。

如果您只想获得amazon结果并将其转换为JSON,那么最好的方法可能是使用瓶鼻[]。我是这样做的

amazon = bottlenose.Amazon(access_key_id, secret_key, associate_tag)
class AmazonProductsViewSet(viewsets.ViewSet):
    def list(self, request, format=None):
        response = amazon.ItemSearch(Keywords="Kindle 3G", SearchIndex="All")
        return Response(xmltodict.parse(response)) #json.dumps(xmltodict.parse(response))

现在,我将整个XML文档作为JSON获取。

不可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)
然后像这样使用它:

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)
希望有帮助