Created
April 18, 2021 17:14
-
-
Save worace/c8424295f1f89bfab384710469a4ed2f to your computer and use it in GitHub Desktop.
stringify non-string values in jsonb
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
-- migrate:up | |
CREATE OR REPLACE FUNCTION with_stringified_values(input jsonb) | |
RETURNS jsonb | |
LANGUAGE plpgsql AS | |
$func$ | |
DECLARE | |
_key text; | |
_value text; | |
_vals text[] := '{}'::text[]; | |
_output jsonb := '{}'::jsonb; | |
BEGIN | |
FOR _key, _value IN | |
SELECT * FROM jsonb_each_text($1) | |
LOOP | |
_vals = array_append(array_append(_vals, _key), _value); | |
END LOOP; | |
RETURN jsonb_object(_vals); | |
END | |
$func$; | |
do $$ | |
begin | |
assert ( | |
select with_stringified_values('{"a":1, "b": "c"}'::jsonb) | |
) = '{"a":"1", "b":"c"}'::jsonb, 'Should convert non-str vals to str'; | |
end; | |
$$; | |
-- migrate:down | |
DROP function with_stringified_values; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment