'convert multiline string to line string

i have a set of data that needs to be in linestring only before being converted to geojson, tried using st_dump to convert the st_makeline portion of the code which works fine but then i am having an issue converting it back to geojson, here is the code " limited to select only on this dataset"

select geo from ( 
SELECT
routeID ,  json_extract(st_asgeojson(st_makeline(array_agg(st_geogpoint(locs.lon, 
locs.lat) order by locs.date))),'$.coordinates' )as geo,
FROM 
howardcounty.routebatches
cross join UNNEST(locations) as locs
where  locs.date between {{start_date}} and {{end_date}} 
group by routeID 
order by routeID
limit 100
)where length(geo) -length(replace(geo,"[","")) > 1+2

this is the error when inserting st_dump

json_extract(st_asgeojson(st_dump(st_makeline(array_agg(st_geogpoint(locs.lon, locs.lat) order by locs.date)))),'$.coordinates' )as geo,

st_dump_error

before json_extract before json extract after json_extract json extract from geojson



Solution 1:[1]

Although it isn't clear from the documentation, the flatten function in the PD Turfjs library does a very good job of this. Pass any "multi" class to it and it will simplify the array structure. It returns a feature collection with the modified record as a member. Example of application here:

   'var pobject=JSON.parse(rec);
//
// flatten and stringify if MultiLineString
//
   if (pobject.geometry.type=="MultiLineString")
   {
      var tmpobj=turf.flatten(pobject);
      rec=JSON.stringify(tmpobj.features[0]);   
   }'

Solution 2:[2]

ST_Dump returns an array of GEOGRAPHY objects, while ST_AsGeoJson converts a single GEOGRAPHY to string. If the desired output shape is for each line in the multilinestring to be on a separate row, the query needs to flatten that array using UNNEST, similar to how locations are UNNEST'ed here.

Sample query

with sample_data as (
    select 1 id, st_geogfromtext('multilinestring((1 2, 3 4), (5 6, 7 8))') lines
)
select id, line
from sample_data d, unnest(st_dump(d.lines)) line

Result:

id  line
1   "LINESTRING(1 2, 3 4)"
1   "LINESTRING(5 6, 7 8)"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ed granzow
Solution 2