'Add ID to GeoJSON using python
I have a GeoJSON file in the following format:
{
"type": "FeatureCollection",
"name": "entities",
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
"features": [
{
"type": "Feature",
"properties": {
"Layer": "111",
"SubClasses": "AcDbEntity:AcDbPolyline",
"EntityHandle": "1E632"
},
"geometry": {
"type": "LineString",
"coordinates": [
[
-5.916278267253799,
54.60546220880693,
-5.5
], etc
I want to add an ID to each feature, e.g. 1, 2, 3, etc
I've tried the following code, which isn't throwing any errors but also isn't adding the ID
#create empty file to be writen to
file = open("new_file.geojson", "w")
count = 0
#read original file
with open('original_file.geojson', 'r')as myfile:
for line in myfile:
#lines that don't need to be edited with an 'id'
if not line.startswith('{ "type": '):
file.write(line)
else:
#lines that need to be edited
count = count +1
idNr = str(count)
file.write(line[0:20] + '"id":'+ '"'+ idNr + '",' +line[21:])
file.close()
Where am I going wrong?
Solution 1:[1]
You can access the dicts keys in this way:
dict_element['key1']['key2']
But how there is some lists inside the dicts, you can access then with the lists index, do this in the right order untill 'features' level:
new_dict = dict_element['<key1>'][<index>]['features']
How the IDs are in the list level, you can just do a for loop in the right level and insert it in the index [0]:
i = 0
for i in range(len(new_dict)):
new_dict[i].insert(0,i+1)
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 | Danrley Perez Sena |
