

Most importantly, we have completely assembled artist objects, with albums available as an array via the albums property on each artist. Voila – we have ready-to-use JSON to return to our application. Example Data from Chinook (modified)įor the examples which follow, I will be using a slightly modified version of the Chinook database, which I tweaked to be a little more Postgres-friendly.Ĭonsider the following tables from Chinook (with Sample Data added): The Chinook Artists and Albums Table


In this post, we’ll take a quick look at the row_to_json() function, the array_to_json() function, and the json_agg() function, and see how between these three we can shape relational data on the database side, possibly in a much more performant manner than we might within our application. Using some of Postgres’ in-built JSON functions in conjunction with the JSON data type, we can compose ready-to-use JSON objects before returning the result. When working in Node.JS, it might be handy to do some heavy lifting via Postgres to reduce some n+1 / lazy loading issues, especially when pulling data for display. Because Postgres can work with both JSON and arrays as first-class data types, it is possible to perform some very handy mappings on the server end which would become potential performance bottlenecks on the client side.
