在我的postgres函数中,我有一组json:
{"layer_name":"rooms","properties":{"fillOpacity":1,"strokeColor":"#606576","strokeWidth":"3"}}
{"layer_name":"map","properties":{"fillColor":"#3D404F"}}
我需要将其修改为结构:
{
"rooms": {"fillOpacity":1,"strokeColor":"#606576","strokeWidth":"3"}},
"map: {"fillColor":"#3D404F"}
}
我试图遍历集合并填充两个数组(一个用于键,其他vor falues),因此我可以使用json_object(keys text[], values text[])
创建所需的json:
CREATE OR REPLACE FUNCTION appearance.get_styles(out response text)
RETURNS text
AS
$BODY$
declare
vResult json;
i json;
keys TEXT[];
vals TEXT[];
layers json;
begin
with a as (SELECT layer_name, properties FROM appearance.styles)
select json_agg(a)
into vResult
from a;
FOR i IN SELECT * FROM json_array_elements(vResult)
LOOP
RAISE NOTICE 'props %', i;
keys = array_append(keys, i->>'layer_name');
vals = array_append(vals, i->>'properties');
END LOOP;
layers = json_object(keys, vals);
RAISE NOTICE 'props %', layers;
response := concat ('"layersStyles"', ':', coalesce(layers::text,'[]'));
response := '{' || response || '}';
end;
$BODY$
LANGUAGE plpgsql VOLATILE SECURITY DEFINER;
但问题是我必须将json
转换为text
,最后我将转义字符串作为值:
"map" : "{\"fillColor\":\"#3D404F\"}", "rooms" : "{\"fillOpacity\":1,\"strokeColor\":\"#606576\",\"strokeWidth\":\"3\"}"}
这不是我需要的。我无法弄清楚如何制作嵌套的json
对象。看不到它的任何功能here。有更好的方法吗?
答案 0 :(得分:0)
在json_object_agg
函数的帮助下解决。
CREATE OR REPLACE FUNCTION appearance.get_styles(out response text)
RETURNS text
AS
$BODY$
declare
vResult json;
begin
SELECT json_object_agg("layer_name", "properties") from appearance.styles
into vResult;
response := concat ('"layersStyles"', ':', coalesce(vResult::text,'[]'));
response := '{' || response || '}';
end;
$BODY$
LANGUAGE plpgsql VOLATILE SECURITY DEFINER;