在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键的第一对坐标值?
发布于 2019-11-23 11:30:21
我猜你的反应是:
[{"area": "abcd", "geojson": "{\"type\": \"MultiPolygon\", ...}"}]JSON中的geojson属性的值本身就是JSON字符串,requests只解析该字符串的第一个“级别”。因此,您将得到Python列表:
[{'area': "abcd', 'geojson': '{"type": "MultiPolygon", ...}'}]如果results[0]['geojson']值仍然是JSON对象字符串,则而不是解析为字典。这解释了错误;'{"type": "MultiPolygon", ...}'['coordinates']试图使用另一个字符串索引字符串,而不是按键访问字典的值:
>>> '{"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
]https://stackoverflow.com/questions/59007051
复制相似问题