[英]String indices must be integers geojson
I am trying to extract coordinates from Geojson in Python, when I am trying to extract coordinates from the entire file it is throwing an error "string indices must be integers".我试图从 Python 中的 Geojson 中提取坐标,当我试图从整个文件中提取坐标时,它抛出一个错误“字符串索引必须是整数”。 But when I am trying to extract single coordinate it runs fine.但是当我尝试提取单个坐标时,它运行良好。
Below code gives correct results as [46.931625, -84.52694]下面的代码给出了正确的结果 [46.931625, -84.52694]
import geojson
with open('output.json') as f:
gj = geojson.load(f)
features = gj['features'][0]
geometry = features['geometry']
geometry['coordinates']
But When I am trying to run through entire file it throws an error但是当我尝试遍历整个文件时,它会引发错误
for feature in gj['features']:
for geometry in feature['geometry']:
for coordinates in geometry:
print(geometry['coordinates'])
sample data is as follows样本数据如下
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
46.931625,
-84.52694
]
},
"properties": {
"event": "a",
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
46.931725,
-84.52684
]
},
"properties": {
"event": "a",
}
}
]
}
Can you please help me with the error.你能帮我解决这个错误吗? Thanks in advance.提前致谢。
Well, feature['geometry']
is a dictionary, so the following line will iterate through keys of that dict:好吧, feature['geometry']
是一个字典,所以下面这行将遍历该字典的键:
for geometry in feature['geometry']:
You are getting that error since geometry
is a key, such as "type"
, which is a string.您会收到该错误,因为geometry
是一个键,例如"type"
,它是一个字符串。 Besides, you don't seem to be using loop variable coordinates
anywhere in your code.此外,您似乎没有在代码中的任何地方使用循环变量coordinates
。
Try the following instead:请尝试以下操作:
for feature in gj['features']:
print(feature["geometry"]['coordinates'])
or better或更好
for feature in gj['features']:
lat, lon = feature["geometry"]['coordinates']
print("Lat:", lat, "Lon: ", lon)
This should result in something like这应该导致类似
('Lat:', 46.931625, 'Lon: ', -84.52694)
('Lat:', 46.931725, 'Lon: ', -84.52684)
features in your sample is the only array object.示例中的 features 是唯一的数组对象。 Loop through features and get the array of coordinates.循环遍历特征并获取坐标数组。
Compressed code:压缩代码:
print([features['geometry']['coordinates'] for features in gj['features']])
This will loop through gj['features']
and print only the features['geometry']['coordinates']
for each of the features.这将遍历gj['features']
并仅打印每个features['geometry']['coordinates']
。
your script would look like this你的脚本看起来像这样
import geojson
with open('output.json') as f:
gj = geojson.load(f)
print([features['geometry']['coordinates'] for features in gj['features']])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.