我是python的新手,我正在处理一些geojson文件,其中包含多个对象,每个对象代表一个区域。我需要打印所有区的坐标,我该怎么做?我正在尝试此操作,但是它不起作用:
import json
with open('districts and precinc data merged.json') as f:
data = json.load(f)
for i in json['features']:
print(i['geometry']['coordinates'])
这是json文件的示例:
{"type":"FeatureCollection", "features": [
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[552346.2856999999,380222.8998000007]]]]},"properties":{"OBJECTID":1,"STFID":"55001442500001","NAME":"0001"}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[529754.7249999996,409135.9135999996],[529740.0305000003,408420.03810000047]]]},"properties":{"OBJECTID":2,"STFID":"55001537250001","NAME":"0001","COUSUBFP":"53725"}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[508795.9363000002,441655.3672000002],[508813.49899999984,441181.034]]]},"properties":{"OBJECTID":6278,"STFID":"55141885750001","NAME":"0001","COUSUBFP":"88575"}}
]}
我想要的输出将是a,每行具有每个对象的坐标,如下所示:
[552346.2856999999,380222.8998000007]
[529754.7249999996,409135.9135999996],[529740.0305000003,408420.03810000047]
[508795.9363000002,441655.3672000002],[508813.49899999984,441181.034]
感谢您的帮助!
答案 0 :(得分:0)
您的json错误。在第一行中,有3个列表打开[[[
,但有4个列表]]]]
。在您的json文件中,将[[[552346.2856999999,380222.8998000007]]]]
替换为[[[552346.2856999999,380222.8998000007]]]
。
然后您可以使用嵌套循环,
x = {"type":"FeatureCollection", "features": [
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[552346.2856999999,380222.8998000007]]]},"properties":{"OBJECTID":1,"STFID":"55001442500001","NAME":"0001"}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[529754.7249999996,409135.9135999996],[529740.0305000003,408420.03810000047]]]},"properties":{"OBJECTID":2,"STFID":"55001537250001","NAME":"0001","COUSUBFP":"53725"}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[508795.9363000002,441655.3672000002],[508813.49899999984,441181.034]]]},"properties":{"OBJECTID":6278,"STFID":"55141885750001","NAME":"0001","COUSUBFP":"88575"}}
]}
for i in x["features"]:
for j in i["geometry"]["coordinates"][0]:
print(j, end=",") # replace `\n` with `,`
print("\b") # removes trailing ,
# output,
[552346.2856999999, 380222.8998000007]
[529754.7249999996, 409135.9135999996],[529740.0305000003, 408420.03810000047]
[508795.9363000002, 441655.3672000002],[508813.49899999984, 441181.034]