Search code examples
pythonjsonserializationshopifyshopify-app

Shopify Python API : How to serialize products list to JSON?


I want to fetch Products list and return as JSON using the Shopify Python API. I tried the .to_json() function

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

Got the error

'PaginatedCollection' object has no attribute 'to_json'

I tried doing

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

Error:

Object of type Product is not JSON serializable

How can I serialize the Products response to JSON ?


Solution

  • You'll need to loop through the list,convert each to dict (to_dict() function) and append to a list.

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

    You can now send productsJSON list as a JSON response.