I guess my question is, to you, what's the main benefit of building JSON in the inthe DB instead of your app?
There is an obvious trade off of flexibility, but this technique is beneficial in that it allows rich object graphs through the ORM where required, while performing well for simple operations.
Now, where I could see returning JSON being really useful is if you can build complex structures out of it, in a way that follows constraints. E.g.
{
"title" : "Cool Hand Luke",
"released" : "1967-11-01",
"cast" : [
{ "name": "Paul Newman" },
{ "name": "George Kennedy" },
...
],
}
If that can be efficiently generated on the DB, that could help immensely with the current state of prefetching relationships, which to my knowledge, currently requires either redundant data through joins, and is thus increasingly inefficient the more items you relate (such as with DBIx::Class's prefetch), or uses multiple queries (ActiveRecord's :include), which includes either processing between queries or duplicating portions of results in subsequent queries to get the correct subset of relations.Now, if you are indeed just passing the JSON directly through to some client further up the stack, there probably is some benefit to generating JSON on the DB, as long as your DB isn't CPU constrained. For any other purpose, I imagine generating JSON would be less space efficient and require additional and/or more onerous steps to converting the record to the appropriate language construct.
With `json_build_object()`, you can select fields as a JSON object and not have to do that JSON building in your app.
Here's a snippet demonstrating building, and then querying a JSON object: