title: TypeError: Object of type <Foo> is not JSON serializable (in Array)
body: <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>Package</th>
  <th>Version</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>Python</td>
  <td>3.9.7</td>
  </tr>
  <tr>
  <td>Flask</td>
  <td>2.0.2</td>
  </tr>
  <tr>
  <td>Flask-UUID</td>
  <td>0.2</td>
  </tr>
  <tr>
  <td>pip</td>
  <td>21.3.1</td>
  </tr>
  <tr>
  <td>setuptools</td>
  <td>57.4.0</td>
  </tr>
  <tr>
  <td>Werkzeug</td>
  <td>2.0.1</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>Hi there,
  although being familiar with other similar concepts in other languages, this leaves me quite stunned ..
  ..  I am writing a little petstore to get familiar with python - more specific flask - and stumble from error to error. The 'normal way to learn I guess  ^.^</p>
  <p>Nevermind, the code is primarily from here (<a href="https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask#creating-the-api" rel="nofollow noreferrer">https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask#creating-the-api</a>) and works fine ..</p>
  <pre class="lang-py prettyprint-override"><code>import flask
  from flask import request, jsonify
  
  app = flask.Flask(__name__)
  app.config[&quot;DEBUG&quot;] = True
  
  # Create some test data for our catalog in the form of a list of dictionaries.
  books = [
      {'id': 0,
       'title': 'A Fire Upon the Deep'},
      {'id': 1,
       'title': 'The Ones Who Walk Away From Omelas'},
      {'id': 2,
       'title': 'Dhalgren'}
  ]
  
  @app.route('/', methods=['GET'])
  def home():
      return '''&lt;h1&gt;Distant Reading Archive&lt;/h1&gt;
  &lt;p&gt;A prototype API for distant reading of science fiction novels.&lt;/p&gt;'''
  
  # A route to return all of the available entries in our catalog.
  @app.route('/api/v1/resources/books/all', methods=['GET'])
  def api_all():
      return jsonify(books)
  
  app.run()
  </code></pre>
  <p>.. but .. instead of a prewritten array I'd like to paste some objects before switching to an sqlite-persisence-solution (or likewise).</p>
  <p>As far as possible I want to raise the complexity slowly to grasp the program completely.</p>
  <p>Hence, using a customized pet class:</p>
  <pre class="lang-py prettyprint-override"><code>import flask
  from flask import request, jsonify
  import uuid
  
  app = flask.Flask(__name__)
  app.config[&quot;DEBUG&quot;] = True
  
  class Pet:
      def __init__(self,id, name, dateOfBirth):
        self.id = id.hex
        self.name = name
        self.dateOfBirth = dateOfBirth
  #    def to_json(obj):
  #        return json.dumps(obj, default=lambda obj: obj.__dict__)
  
  # Create some test data for our catalog in the form of a list of dictionaries.
  pets = [ Pet(uuid.uuid4(),'Hamster', '02.12.2019' )]
  pets.append( Pet(uuid.uuid4(),'Fish', '07.03.1985' ))
  pets.append( Pet(uuid.uuid4(),'Dog', '26.11.2000' ))
  pets.append( Pet(uuid.uuid4(),'Cat', '17.05.2021' ))
  
  @app.route('/', methods=['GET'])
  def home():
      return &quot;&lt;h1&gt;Petshop Archive&lt;/h1&gt;&lt;p&gt;This site is a prototype API for the petshop archive.&lt;/p&gt;&quot;
  
  # A route to return all of the available entries in our catalog.
  @app.route('/api/v1/resources/pets/all', methods=['GET'])
  def api_all():
      return jsonify(pets)
  
  if __name__ == '__main__':
      app.run(host='0.0.0.0')
  </code></pre>
  <p>.. You see, the changes are marginal.
  Now, requesting the API ( http://localhost:5000/api/v1/resources/pets/all ) fails giving a &quot;TypeError: Object of type Pet is not JSON serializable&quot; from the line ..</p>
  <pre class="lang-py prettyprint-override"><code>return jsonify(pets)
  </code></pre>
  <p>.. fair enough.
  Of course I googled and found fitting solutions, such as ..</p>
  <ol>
  <li><a href="https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable">How to make a class JSON serializable</a></li>
  </ol>
  <p>.. and ..</p>
  <ol start="2">
  <li><a href="https://stackoverflow.com/questions/39827862/python-json-object-array-not-serializable">python json object array not serializable</a></li>
  </ol>
  <p>.. for the serializable problem (generally) and added the appropriate function</p>
  <pre class="lang-py prettyprint-override"><code>def to_json(obj):
          return json.dumps(obj, default=lambda obj: obj.__dict__)
  </code></pre>
  <p>Still I missed the link between the function (serializing the pet-class) and the array (recognizing the pet class to be serializabe).</p>
  <p>My approach to write a new array to prevent any class having to be serialized by returning 'pets[pet]' ..</p>
  <pre class="lang-py prettyprint-override"><code>def api_all():
      allpets = [pet.toJson for pet in pets]
      return jsonify(allpets)
  </code></pre>
  <p>.. fails as well.</p>
  <p>Hence the -&gt; <strong>TypeError: Object of type Pet is not JSON serializable</strong> &lt;- still exists.</p>
  <p>Is there 'fancy way' to solve this issue?
  I can't imagine that this issue has not been raised, yet.
  Maybe I just looked at it from a wrong angle   ;-)</p>
  <p>Thanks everyone who made it this far   :)</p>