J
J
Jason dinAlt2021-01-05 19:49:39
PostgreSQL
Jason dinAlt, 2021-01-05 19:49:39

Postgres - how to rename object keys in jsonb array in a loop?

Let's say we have an array of elements like this:

[{
"some_key" : 5,
"another_key" : {
            nested_key: "value"
       },
},
{
"some_key" : 231,
"another_key" : {
            nested_key: "data"
       },
}]

The essence of the task is to convert all keys to camel case (including nested ones), i.e. bring each object of the array to this form:
{
"someKey" : 231,
"anotherKey" : {
            nestedKey: "data"
       },
}

I have already written a function for translating strings into camel case. I don't know how to rename object keys in a loop
Help, please, I've been suffering for 4 days already. Here is what I have now:
create or replace function jsonb_arr_to_camel_case(j_array jsonb)
returns jsonb
as $$
declare 
  el jsonb;
  new_obj jsonb;
  text_arr text[];
  new_arr jsonb[];
  i record;
begin
  for el in select * from jsonb_array_elements(j_array)
  loop
    for i in select * from jsonb_each_text(el)
          loop
                       --do some logic here
      el := el::jsonb - i.key || jsonb_build_object(to_camel_case(i.key), i.value);
      end loop;
            -- do some logic here
  end loop;
  return j_array;
end;
$$ language plpgsql stable;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question