Postgres multiple columns to json

There is a better option with json_build_object() in Postgres 9.4+:

SELECT id, json_build_object('name', name, 'addr', addr) AS data
FROM   myt;

But there is also a simpler and faster way with row_to_json() in Postgres 9.3:

SELECT id, row_to_json((SELECT d FROM (SELECT name, addr) d)) AS data
FROM   myt;

db<>fiddle here
Old SQL Fiddle on Postgres 9.6.

Related answers:

  • Select columns inside json_agg

  • Return as array of JSON objects in SQL (Postgres)

  • Return total number of rows and selected (aggregated) data


I found the answer from this link:

select * from (
  select id,
    (
      select row_to_json(d)
      from (
        select name, addr
        from myt d
        where d.id=s.id
      ) d
    ) as data
  from myt s
)