-
-
Save kenaniah/1315484 to your computer and use it in GitHub Desktop.
hstore to json function for postgresql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION public.hstore2json ( | |
hs public.hstore | |
) | |
RETURNS text AS | |
$body$ | |
DECLARE | |
rv text; | |
r record; | |
BEGIN | |
rv:=''; | |
for r in (select key, val from each(hs) as h(key, val)) loop | |
if rv<>'' then | |
rv:=rv||','; | |
end if; | |
rv:=rv || '"' || r.key || '":'; | |
--Perform escaping | |
r.val := REPLACE(r.val, E'\\', E'\\\\'); | |
r.val := REPLACE(r.val, '"', E'\\"'); | |
r.val := REPLACE(r.val, E'\n', E'\\n'); | |
r.val := REPLACE(r.val, E'\r', E'\\r'); | |
rv:=rv || CASE WHEN r.val IS NULL THEN 'null' ELSE '"' || r.val || '"' END; | |
end loop; | |
return '{'||rv||'}'; | |
END; | |
$body$ | |
LANGUAGE 'plpgsql' | |
IMMUTABLE | |
CALLED ON NULL INPUT | |
SECURITY INVOKER | |
COST 100; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I created an alternative to this thing, it supports some extra types aswell :
https://gist.github.com/2318757