encoding books into json this approach certainly works and provides very lightweight way to convert book into json howeverthe approach presented above does mean that every time we want to jsonify book we must remember to call the to_json(method in some cases this means that we will also have to write some slightly convoluted code for example if we wish to return list of books from the bookshop as json list we might writejsonify({'books'[ to_json(for in bookshop books]}here we have used list comprehension to generate list containing the json versions of the books held in the bookshop this is starting to look overly complexeasy to forget about and probably error prone flask itself uses encoders to encode types into json flask provides way of creating your own encoders that can be used to convert custom typesuch as the book classinto json such an encoder can automatically be used by the jsonify(function to do this we must implement an encoder classthe class will extend the flask json jsonencoder superclass the class must define method default(selfobjthis method takes an object and returns the json representation of that object we can therefore write an encoder for the book class as followsclass bookjsonencoder(jsonencoder)def default(selfobj)if isinstance(objbook)return 'isbn'obj isbn'title'obj title'author'obj author'price'obj price elsereturn super(bookjsonencoderselfdefault(objthe default(method in this class checks that the object passed to it is an instance of the class book and if it is then it will create json version of the book this json structure is based on the isbntitleauthor and price attributes if it is not an instance of the book classthen it passes the object up to the parent class we can now register this encoder with the flask application object so that it will be used whenever book must be converted into json this is done by assigning the custom encoder to the flask application object via the app json_encoder attribute