Skip to content

Instantly share code, notes, and snippets.

@kashif
Created June 17, 2011 10:26
Show Gist options
  • Save kashif/1031178 to your computer and use it in GitHub Desktop.
Save kashif/1031178 to your computer and use it in GitHub Desktop.
hstore to json function from Ilya Kosmodemiansky
CREATE FUNCTION public.hs_2json(hs hstore) RETURNS text AS $$
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 || '":';
rv:=rv || '"' || regexp_replace(regexp_replace(r.val,$$\\$$,$$\\\\$$,'g'),'"', $$\"$$,'g') || '"';
end loop;
return '{'||rv||'}';
END;
$$ LANGUAGE plpgsql IMMUTABLE;
@booo
Copy link

booo commented Jul 21, 2011

You missed the count in line 6 ;)

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