I have converted kml files to GeoJSON strings. These represent polygons that are often not closed. I want to enforce their closing by searching for the first lat/lon coordinate in the string, checks if this matches with the last coordinate string, and if not, plot the first coordinate string behind the last coordinate string. An example:

textstring = '''{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[**-76.863853437826,2.49314161017537**],[-76.863723769784,2.4932265188545],[-76.8627395667136,2.49319550581276],[**-76.863855677,2.49314156433**]]]},"properties":{"pointCount":"3","length":"0.0","area":"0.00001"}}]}'''

In this string you see that the first coordinate does not match the last coordinate (open polygon).

I used this regex code to find the first coordinate, but it is not robust because it does not respond well on coordinates having or not having a negative (-) sign:

import re

textstring = '''{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-76.863853437826,2.49314161017537],[-76.863723769784,2.4932265188545],[-76.8627395667136,2.49319550581276],[-76.863855677,2.49314156433]]]},"properties":{"pointCount":"3","length":"0.0","area":"0.00001"}}]}'''

coord_first = re.search(r'(-[0-9.]+|[0-9.]+,[0-9.]+|-[0-9.]+)',textstring)

1 Answer 1


GeoJSON is JSON data, it's easier if you treat it as such. Actually it's probably better to treat it as geospatial data and use a geospatial library, but if you're stuck with the standard library:

import json
str_data = '''{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-76.863853437826,2.49314161017537],[-76.863723769784,2.4932265188545],[-76.8627395667136,2.49319550581276],[-76.863855677,2.493141564331234]]]},"properties":{"pointCount":"3","length":"0.0","area":"0.00001"}}]}'''
json_data = json.loads(str_data)

for feature in json_data['features']:
    for linestring in feature['geometry']['coordinates']:
        first_coord = linestring[0]
        last_coord = linestring[-1]
        if first_coord != last_coord:


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.