首页 > 解决方案 > Shopify Python API:如何将产品列表序列化为 JSON?

问题描述

我想使用 Shopify Python API 获取产品列表并以 JSON 形式返回。我尝试了 .to_json() 函数

products=shopify.Product.find().to_json()

得到错误

'PaginatedCollection' object has no attribute 'to_json'

我试着做

products=shopify.Product.find()
js=json.dumps(products)

错误:

Object of type Product is not JSON serializable

如何将 Products 响应序列化为 JSON ?

标签: pythonjsonserializationshopifyshopify-app

解决方案


您需要遍历列表,将每个转换为 dict(to_dict() 函数)并附加到列表中。

products=shopify.Product.find()
productsJSON=[]
for product in products:
    productsJSON.append(product.to_dict())

您现在可以将 productsJSON 列表作为 JSON 响应发送。


推荐阅读