This can be achieved using partials.
See the example below with _book.json.jbuilder and a _library.json.jbuilder partials.
More documentation here: https://github.com/rails/jbuilder
# books/_book.json.jbuilder
json.id book.id
json.title book.title
json.author book.author
# books/index.json.jbuilder
json.array! @books, partial: 'books/book', as: :book
# libraries/_library.json.jbuilder
json.id library.id
json.title library.name
json.books library.books, partial: 'books/book', as: :book
# libraries/index.json.jbuilder
json.array! @libraries, partial: 'libraries/library', as: :library