Skip to content

Instantly share code, notes, and snippets.

@worace
Created April 18, 2021 17:14
Show Gist options
  • Save worace/c8424295f1f89bfab384710469a4ed2f to your computer and use it in GitHub Desktop.
Save worace/c8424295f1f89bfab384710469a4ed2f to your computer and use it in GitHub Desktop.
stringify non-string values in jsonb
-- 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