Skip to content

Instantly share code, notes, and snippets.

@nickell
Last active June 19, 2020 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nickell/e33c78fe475fc1aee87ae9d7ba6f42f7 to your computer and use it in GitHub Desktop.
Save nickell/e33c78fe475fc1aee87ae9d7ba6f42f7 to your computer and use it in GitHub Desktop.
create or replace function camelize(text)
returns text as $$
declare parts text[] = string_to_array($1, '_');
declare capitalized_parts text[] = (select array_agg(initcap(n)) from unnest(parts) as n);
begin
return parts[1] || array_to_string(capitalized_parts[2:], '');
end;
$$ language plpgsql;
create or replace function camelize_keys(json)
returns json as $$
declare i text;
declare x jsonb = '{}'::jsonb;
begin
for i in (select * from json_object_keys($1)) loop
x = jsonb_set(x, ARRAY[camelize(i)], ($1->i)::jsonb);
end loop;
return to_json(x);
end;
$$ language plpgsql;
create or replace function jsonb_camelize_keys(jsonb)
returns json as $$
begin
return camelize_keys(to_json($1));
end;
$$ language plpgsql;
create or replace function camelize_array(json) returns json as $$
declare i json;
declare x json[];
begin
for i in (select * from json_array_elements($1)) loop
x = array_append(x, camelize_keys(i));
end loop;
return to_json(x);
end;
$$ language plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment