Returning JSON directly from PostgreSQL
I’m creating a lot of JSON APIs using Grape or Ruby on Rails lately. From time to time I’m facing an issue when I need to return a large amount of data in a single response.
The usual way would be to execute query via ActiveRecord and use some library like JBuilder or ActiveModelSerializers to generate JSON response. It’s nice and easy but sometimes too slow :(
In situation like this I’m relying on PostgreSQL to help me out with it’s row_to_json function.
Let’s convert the chart query from my previous post so it can return json that is ready to send to the chart library right away:
The best part is that JSON serialization overhead comparing to the original query is almost invisible!