select columns into a json from postgres
我有一个像这样的表员工
1 2 3 4 | name VALUE 'e1' 'rahul' 'e2' 'priya' 'e3' 'abhijit' |
我需要从两列中提取json,结果就像这样
1 | {'e1':'rahul','e2':'priya','e3':'abhijit'} |
我尝试了以下查询,结果如下
1 2 3 4 5 6 7 | SELECT row_to_json((name,VALUE)) FROM employee O/P {'f1':'e1','f2':'rahul'} {'f2':'e1','f2':'priya'} {'f3':'e1','f2':'abhijit'} |
我不想那边的f1和f2名字,请指教!
感谢输入人员,但我发现我必须将postgresql从9.3升级到9.4才能获得函数json_build_object。通过对查询结构进行一些更改来完成工作。
1 2 3 | SELECT json_agg(json_build_object(name,VALUE)) FROM employee; [{'e1':'rahul','e2':'priya','e3':'abhijit'}] |
1 | SELECT ROW_TO_JSON(a) FROM (SELECT name, VALUE FROM employee) a; |
如果我正确地得到了您的问题,那么,如此处所述,在postgres 9.4+中您可以使用
1 2 | CREATE temp TABLE employee AS (SELECT 'key'::text AS name, 'val'::text AS VALUE); SELECT json_build_object(name,VALUE) FROM employee; |
结果如下:
1 2 3 | json_build_object ------------------- {"key" :"val"} |