Created
May 26, 2020 15:44
-
-
Save vierarb/3518e28d23448e3380e43e9eb79e50a2 to your computer and use it in GitHub Desktop.
Postgres: convert text to array of JSONs by regular expression
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 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