3

I've created this two functions, and I want to know if there is a better way to cast json arrays to polygons without having to install the PostGIS extension.

Raw type:

((-34.888733,-57.956764),(-34.92303,-57.99367),(-34.953579,-57.95255))

polygon_to_json:

["-34.888733,-57.956764","-34.92303,-57.99367","-34.953579,-57.95255"]

json_to_polygon:

((-34.888733,-57.956764),(-34.92303,-57.99367),(-34.953579,-57.95255))

create or replace function json_to_polygon(p_poly json, out p_out polygon) returns polygon
parallel safe
returns null on null input
immutable
language plpgsql
as $$
begin
 if(p_poly is null) then
 return;
 end if;
 select
 polygon(concat('((', string_agg(x, '),('), '))'))
 from
 json_array_elements_text(p_poly) x
 into
 p_out;
end;
$$;
create or replace function polygon_to_json(p_poly polygon) returns json
parallel safe
returns null on null input
immutable
language plpgsql
as $$
begin
 if(p_poly is null) then
 return null;
 end if;
 return to_json(string_to_array(replace(replace(p_poly::text, '((', ''), '))', ''), '),('));
end;
$$;
Erwin Brandstetter
186k28 gold badges463 silver badges636 bronze badges
asked Aug 12, 2024 at 21:21
0

1 Answer 1

1

Yes, there is a better way:

CREATE OR REPLACE FUNCTION json_to_polygon (p_poly json)
 RETURNS polygon
 LANGUAGE sql PARALLEL SAFE STRICT IMMUTABLE
RETURN replace(replace(replace(
 p_poly::text
 , '","', '),(')
 , '["', '((')
 , '"]', '))')::polygon;
CREATE OR REPLACE FUNCTION polygon_to_json (p_poly polygon)
 RETURNS json
 LANGUAGE sql PARALLEL SAFE STRICT IMMUTABLE
RETURN replace(replace(replace(
 p_poly::text
 , '),(', '","')
 , '((' , '["')
 , '))' , '"]')::json;

fiddle

All that said, PostGIS does have some functions to help with that ...

answered Aug 16, 2024 at 2:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.