Skip to content

Instantly share code, notes, and snippets.

@kenaniah
Forked from booo/hs_2json.sql
Created October 26, 2011 04:59
Show Gist options
  • Save kenaniah/1315484 to your computer and use it in GitHub Desktop.
Save kenaniah/1315484 to your computer and use it in GitHub Desktop.
hstore to json function for postgresql
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;
@wolph
Copy link

wolph commented Apr 6, 2012

I created an alternative to this thing, it supports some extra types aswell :

https://gist.github.com/2318757

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment