Skip to content

Instantly share code, notes, and snippets.

@vierarb
Created May 26, 2020 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vierarb/3518e28d23448e3380e43e9eb79e50a2 to your computer and use it in GitHub Desktop.
Save vierarb/3518e28d23448e3380e43e9eb79e50a2 to your computer and use it in GitHub Desktop.
Postgres: convert text to array of JSONs by regular expression
CREATE OR REPLACE FUNCTION text_to_json(text text, regex varchar) RETURNS json[] AS $$
DECLARE
chunk text;
res json[];
BEGIN
FOREACH chunk IN array regexp_split_to_array(text, regex)
LOOP
IF TRIM(chunk) <> '' THEN
BEGIN
res := res || chunk::json;
EXCEPTION
WHEN invalid_text_representation THEN
RETURN ARRAY[to_json(text)];
END;
END IF;
END LOOP;
RETURN res;
END; $$
LANGUAGE 'plpgsql';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment