Skip to content

Instantly share code, notes, and snippets.

@gustavomedeiross
Created July 26, 2024 15:42
Show Gist options
  • Save gustavomedeiross/3139975c92cf02c9a82ed97733dbc0ad to your computer and use it in GitHub Desktop.
Save gustavomedeiross/3139975c92cf02c9a82ed97733dbc0ad to your computer and use it in GitHub Desktop.
Truncate large JSONs in psql
CREATE OR REPLACE FUNCTION truncate_large_fields(
json_data jsonb,
max_length int DEFAULT 100
) RETURNS jsonb AS $$
DECLARE
key text;
value jsonb;
result jsonb := '{}';
BEGIN
FOR key, value IN SELECT * FROM jsonb_each(json_data)
LOOP
IF jsonb_typeof(value) = 'string' AND length(value::text) > max_length THEN
result := result || jsonb_build_object(key, substr(value::text, 1, max_length) || '...');
ELSIF jsonb_typeof(value) = 'object' THEN
result := result || jsonb_build_object(key, truncate_large_fields(value, max_length));
ELSIF jsonb_typeof(value) = 'array' THEN
result := result || jsonb_build_object(key, (
SELECT jsonb_agg(truncate_large_fields(element, max_length))
FROM jsonb_array_elements(value) AS element
));
ELSE
result := result || jsonb_build_object(key, value);
END IF;
END LOOP;
RETURN result;
END;
$$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment