解析json字典列表

时间:2019-11-23 11:17:59

标签: python json parsing

我试图在api调用后从字典的json列表中检索每个区域的面积值和第一对坐标值

[{'area': 'abcd', 'geojson': '{"type":"MultiPolygon","coordinates":[[[[103.8593,1.43905,...[103.6391,1.3527]]]]}'},
 {'area': 'efgh', 'geojson': '{"type":"MultiPolygon","coordinates":[[[[100.000,1.4000,...[103.6391,1.3527]]]]}'}
.
.

这是我的代码

# calling the API 
results = requests.get(url).json()

area= []
coordinates = []

for i in results:
    a = i['pln_area_n'] 
    area.append(a)

for x in results:
    c = x['geojson']['coordinates'][0]
    coordinates.append(c)

TypeError: string indices must be integers

我的代码肯定是错误的,如何访问每个区域的geojson键的第一对坐标值?

1 个答案:

答案 0 :(得分:-1)

我猜你的回答是这样的:

[{"area": "abcd", "geojson": "{\"type\": \"MultiPolygon\", ...}"}]

JSON {em>中的geojson属性的值本身就是JSON字符串,而requests将仅解析其第一个“级别”。因此,您最终得到了Python列表:

[{'area': "abcd', 'geojson': '{"type": "MultiPolygon", ...}'}]

其中results[0]['geojson']值仍然是JSON对象字符串,不是解析为字典。这说明了错误; '{"type": "MultiPolygon", ...}'['coordinates']尝试使用另一个字符串索引到 string 中,而不是通过键访问字典的值:

>>> '{"type": "MultiPolygon", ...}'['coordinates']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

因此,您需要import json并再次解析JSON字符串值,例如使用列表理解:

coordinates = [
    json.loads(result['geojson'])['coordinates'][0]
    for result in results
]