5

i have a table employee like this

name     value 
'e1'     'rahul'
'e2'     'priya'
'e3'     'abhijit'

and i need to extract json from the two columns such that the result is like this

{'e1':'rahul','e2':'priya','e3':'abhijit'}

I've tried the following query and the results is as follows

select row_to_json((name,value)) from employee 

O/P

{'f1':'e1','f2':'rahul'}
{'f2':'e1','f2':'priya'}
{'f3':'e1','f2':'abhijit'}

i don't want the f1 and f2 names over there,please advice!

Ashish Padakannaya
  • 463
  • 2
  • 7
  • 17

3 Answers3

13

thanks for the inputs guys but i just found out that i had to upgrade postgresql from 9.3 to 9.4 to get the function json_build_object .it gets the job done with a few changes to the query structure.

select json_agg(json_build_object(name,value)) from employee;

[{'e1':'rahul','e2':'priya','e3':'abhijit'}]
Ashish Padakannaya
  • 463
  • 2
  • 7
  • 17
11
SELECT ROW_TO_JSON(a) FROM (SELECT name, value FROM employee) a;
Dmitry Umarov
  • 426
  • 3
  • 5
2

If I get your question correctly, then, as mentioned here, in Postgres 9.4+ you might use json_build_object():

create temp table employee as (select 'key'::text as name, 'val'::text as value);
select json_build_object(name,value) from employee;

Here is the result:

json_build_object
-------------------
 {"key" : "val"}
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
overdawn
  • 321
  • 3
  • 10