2

I want to try and split a GeoJSON FeatureCollection into the individual features. So that the name of the file I write to is the "ED_ID" field. So far I can only read the JSON.

I am new to python and programming in general.

import json
with open('ded.geojson') as f:
data = json.load(f)

My data looks like this I have pulled out most of the coordinate data and this is one feature the file contains multiple features which I wish to separate.

 {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"OBJECTID_12":3001,"ED_ID":"197023","ED_ENGLISH":"BREEDOGE","ED_GAEILGE":" ","COUNTY":"ROSCOMMON","CONTAE":"Ros Comáin","PROVINCE":"Connacht","CENTROID_X":"573408","CENTROID_Y":"796269","OBJECTID":927,"ED_ID_1":"197023","FIRST_COUNTY":"ROSCOMMON","FIRST_CONTAE":"Ros Comáin","FIRST_PROVINCE":"Connacht","FIRST_ED_ENGLISH":"BREEDOGE","FIRST_ED_GAEILGE":" ","MaxSimpTol":100,"MinSimpTol":100,"GUID":"2AE196291AE513A3E055000000000001","ObjectID_1":927,"Shape__Area":0.00260221958729151,"Shape__Length":0.361585766792224},"geometry":{"type":"Polygon","coordinates":[[[-8.40526490835231,53.926763221445],[-8.39132968800989,53.9252835371864],[-8.38738628086417,53.9256611572713],[-8.38443774016629,53.927271794708],[-8.37396157235263,53.9250928131867]]]}}

1 Answer 1

4

The following code should do what you want. There might be a slightly more elegant way to write it, but I understand your request to pull out each polygon into their own file.

import json
import os

directory = "c:/temp/json"

with open(os.path.join(directory, 'geo.json')) as f:
    d = json.load(f)

for part in d['features']:
    fName = part["properties"]["ED_ID"]
    output = {"type":'FeatureCollection',
        "features": [{       
            "type": 'Feature',
            "properties": part['properties'],
            "geometry": {
                "type": 'Polygon',
                "coordinates": part['geometry']['coordinates']
            }
            }]
        }
    with open(os.path.join(directory, fName + ".json"), 'w', encoding='utf-8') as f_out:
        json.dump(output, f_out, ensure_ascii=False, indent=4)
    print(json.dumps(output))

#print(d)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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