从包含多个json对象的json文件中获取值

时间:2018-11-16 03:54:56

标签: python json geojson

我是python和json的新手,我试图为存储的每个对象获取一个特定的值。我正在尝试打印“ NAME”和“ OBJECTID”下的所有属性存储。我怎样才能做到这一点?我一直在寻找不同的答案,但我仍然感到困惑。 (编辑:整个文件中的大多数对象都有不同的名称,我的目标是创建所有名称的列表。) 这是我正在使用的文件的一个小样本。 谢谢您的帮助!

    {"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"}}
]}

1 个答案:

答案 0 :(得分:0)

假设您的json很像

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"}}
            ]}

您可以使用类似这样的列表理解来获取带有OBJECTID,NAME的元组列表:

oid_name = [(feature['properties']['OBJECTID'], feature['properties']['NAME']) for feature in json['features']]

评估为

[(1, '0001'), (2, '0001'), (6278, '0001')]

在此示例中。

如果您需要查找对象的名称,则可能会发现使用字典对此更有用:

names = {feature['properties']['OBJECTID']: feature['properties']['NAME'] for feature in json['features']}

这将允许您查找如下名称:

>>> names[1]
'0001'