0

I am trying to format a column which is string type with another column which is json or array type.

For example;

String column is like "I am a %s, and I am very good %s" and array like ["student", "at math"].

or

String like "I am a {key1}, and I am very good {key2}" and json like {"key1": "student", "key2": "at math"}

I want to format string column with this second column.

Is it possible to do something like this with PostgreSQL also if it is possible with SQLAlchemy that is better for me.

0

1 Answer 1

1

I can't think of an easy way to do this in plain SQL, so I would write a function for this:

create or replace function fill_placeholders(p_text text, p_parameters jsonb)
  returns text
as
$$
declare
  l_index int;
  l_result text := p_text;
  l_element record;
begin
  if jsonb_typeof(p_parameters) = 'array' then  
    for l_index in 0..jsonb_array_length(p_parameters) - 1 loop
      raise notice '%', l_result;
      l_result := regexp_replace(l_result, '(\%s)', p_parameters ->> l_index);
    end loop;
  else
    for l_element in select * from jsonb_each_text(p_parameters) as x(key,value) loop
      l_result := replace(l_result, '{'||l_element.key||'}', l_element.value);
    end loop;
  end if;
  return l_result;
end;
$$
language plpgsql;

The the following queries:

select fill_placeholders('I am a %s, and I am very good %s', '["student", "at math"]');

select fill_placeholders('I am a {key1}, and I am very good {key2}', '{"key1": "student", "key2": "at math"}');

will both return: I am a student, and I am very good at math

Sign up to request clarification or add additional context in comments.

2 Comments

Firstly, thank you. I am using ORM and using function is not easy for me because I am not familiar with it. Can I do in select statement? Also one option is OK for me. I will write from scratch, which option is better I will use it (Array or Dict).
Just create the function, then you can use it in a SELECT statement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.