【问题标题】:Extracting specific .json data with python使用python提取特定的.json数据
【发布时间】:2020-07-13 19:36:47
【问题描述】:

我有一些看起来像这样的 json 数据:

'{"type": "FeatureCollection",
 "features": [{"id": "0",
               "type": "Feature",
               "properties": {},
               "geometry": {"type": "Polygon",
                            "coordinates": [
                                [[-2.9611591576420615, 53.43052239401445], 
                                 [-2.9602608423579424, 53.43052239401445],
                                 [-2.9602608423579424, 53.4310576043007],
                                 [-2.9611591576420615, 53.4310576043007],
                                 [-2.9611591576420615, 53.43052239401445]]
                             ]}
                }]
   }'

我希望我的代码能够按原样仅检索“坐标”,因此我尝试使用此代码:

points = json_data['features']['geometry']['coordinates']
print(points)

但是当我运行它时,我得到了这个错误:TypeError: string indices must be integers 我已经尝试了很多方法来尝试解决这个问题,但没有成功,所以我想知道是否有人知道我该如何解决这个问题? 提前致谢!

【问题讨论】:

  • 那不是json,是字符串。您需要先将其解析为对象。
  • json_data['features'][0]['geometry']['coordinates']
  • “解析成对象”是什么意思?
  • 另外,@OlvinR​​oght 添加 [0] 仍然给我一个打字错误
  • x = json.loads(json_data)

标签: python json dataframe typeerror


【解决方案1】:

你很亲密:)

所有坐标

['features'][0]['geometry']['coordinates'][0]

目标坐标

['features'][0]['geometry']['coordinates'][0][0]
['features'][0]['geometry']['coordinates'][0][1]
['features'][0]['geometry']['coordinates'][0][n]

但首先你需要解析成python dict。

with open('data.json') as json_file: 
    data = json.load(json_file) 
print(data['features'][0]['geometry']['coordinates'][0])

【讨论】:

  • 我有点合并了你们两个人的答案。我使用 ['features'][0]['geometry']['coordinates'][0] 以我想要的方式打印数据,并使用 json_obj = json.loads(json_data) 正确访问数据跨度>
  • @Barmar 你应该更正你的代码 ['features'][0]['geometry']['coordinates'][0]
  • 为什么?如果列表中有更多元素怎么办?
  • 您没有收到 TypeError?好的,那么
【解决方案2】:

您需要将 JSON 解析为 Python 对象。

import json

json_data = '''{"type": "FeatureCollection",
 "features": [{"id": "0",
               "type": "Feature",
               "properties": {},
               "geometry": {"type": "Polygon",
                            "coordinates": [
                                [[-2.9611591576420615, 53.43052239401445], 
                                 [-2.9602608423579424, 53.43052239401445],
                                 [-2.9602608423579424, 53.4310576043007],
                                 [-2.9611591576420615, 53.4310576043007],
                                 [-2.9611591576420615, 53.43052239401445]]
                             ]}
                }]
   }'''
json_obj = json.loads(json_data)
points = json_obj['features']['geometry']['coordinates']
print(points)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-29
    • 2021-07-01
    • 1970-01-01
    • 2016-10-18
    • 2022-11-21
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多