Skip to content
Advertisement

Python TypeError: object is not iterable,

I am kinda new to python and trying to create a DTO that minimizes the amount of properties exposed from my api. I use an Azure table storage to get records and then loop over it to create a smaller object omiting properties. Though somewhere in the process I get: “TypeError: ‘AbbreviatedPackage’ object is not iterable”

In my main I have the follwing call:

JavaScript

The query_packages_storage()

JavaScript

AbbreviatedPackage class

JavaScript

When I debug the json_entitiesobject gets filled properly enter image description here

Any help would be much sppreciated. Cheers

** Edit

I get the errors while being in the loop enter image description here

JavaScript

Advertisement

Answer

Your AbbreviatedPackage object can’t be converted to JSON automatically. When you run json.dumps with your list of AbbreviatedPackage objects they shouldn’t be serializable by default, throwing this error (as each object is trying to be iterated over and does not have an __iter__ method).

A few options:

  1. Use the .__dict__ method for your object when appending to your list. I personally don’t like this solution, as it’s uncontrolled.
  2. Write __iter__, __str__, and __repr__ methods to properly serialize to JSON along with a CustomEncoder for the json.dumps cls attribute:
JavaScript

Reference: https://changsin.medium.com/how-to-serialize-a-class-object-to-json-in-python-849697a0cd3#8273

And the CustomEncoder class:

JavaScript

I did a full synthesis on this with code:

Advertisement