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

get a value from a json file that contains multiple json objects

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

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

假设你的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'