Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to eliminate newline inside json into one line?

pg12, have this function to extract only text created by Quill Editor:

CREATE OR REPLACE FUNCTION public.fun(
    j json)
    RETURNS text
    LANGUAGE 'plpgsql' immutable
AS $BODY$
begin
  return string_agg((obj->>'insert') || ' ', '')
  FROM json_array_elements(j->'ops') obj;
end;
$BODY$;

select * from fun('{"ops":[{"insert":"1st line\n."},{"insert":"2nd line."},{"insert":"333"}]}') returns

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

return string_agg(replace((obj->>'insert')::text, '\n', '') || ' ', '') won’t do the trick.

How to achieve?
1st line. 2nd line. 333

>Solution :

Use the function replace().

...
begin
  return string_agg(replace(obj->>'insert', e'\n', '') || ' ', '')
...

From the documentation:

PostgreSQL also accepts “escape” string constants, which are an extension to the SQL standard. An escape string constant is specified by writing the letter E (upper or lower case) just before the opening single quote, e.g., E’foo’.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading