Sample Header Ad - 728x90

Cast polygon to json array and json array to polygon

3 votes
1 answer
95 views
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;
$$;
Asked by Leonel Franchelli (33 rep)
Aug 12, 2024, 09:21 PM
Last activity: Aug 16, 2024, 02:54 AM