Skip to content
Advertisement

How to transform a postgresql select with join to a json object?

I want to transform the result from a select with joins into a json object. I mean this query:

should output this:

(there are more fields than these. I’m just making the example simple)

I found a solution this way:

But I think there should be a much better way to do this. Imagine that chat_messages had a lot more fields. It would be lengthy to describe field by field. What I want is a way to for the query to transform subqueries in json without me describing field by field. Anyone knows a better way to do this ?

Advertisement

Answer

According to, Postgres document you can use the row_to_json function to transfer row to JSON and then append each table rows with an alias to be detected by row_to_json

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement