Create json with column values as object keys

json, postgresql, postgresql-9.3

Solution

If you're on 9.4 you can do the following:

$ select json_object_agg("name", "value") from data_table;
           json_object_agg
----------------------------------------------
{ "key_1" : "value_1", "key_2" : "value_2" }

Problem

I have a table defined like this: ``` CREATE TABLE data_table AS ( id bigserial, "name" text NOT NULL, "value" text NOT NULL, CONSTRAINT data_table_pk PRIMARY KEY (id) ); INSERT INTO data_table ("name", "value") VALUES ('key_1', 'value_1'), ('key_2', 'value_2'); ``` I would like to get a JSON object from this table content, which will look like this: ``` { "key_1":"value_1", "key_2":"value_2" } ``` Now I'm using the client application to parse the result set into JSON format. Is it possible to accomplish this by a postgresl query?

Original source