Sometimes, we want to jsonify a list of objects with Python Flask.
In this article, we’ll look at how to jsonify a list of objects with Python Flask.
How to jsonify a list of objects with Python Flask?
To jsonify a list of objects with Python Flask, we add a method in our object’s class to return the object’s contents as a dictionary.
For instance, we write
class Gene(object):
#...
def serialize(self):
return {
'gene_id': self.gene_id,
'gene_symbol': self.gene_symbol,
'p_value': self.p_value,
}
to create the Gene
class that has the serialize
method that returns the instance properties in a dictionary.
Then we call serialize
to return the dictionaries by and put them in a list by writing.
jsonify(eqtls=[e.serialize() for e in my_list_of_eqtls])
where e
is a Gene
instance in the my_list_of_eqtls
list.
We call jsonify
with the list set as the value of the eqtls
argument to return a JSON response with the list of dicts.
Conclusion
To jsonify a list of objects with Python Flask, we add a method in our object’s class to return the object’s contents as a dictionary.