我正在从API JSON响应索引,如下所示:
[{
"id": 1
"name": "Gimbal HQ",
"addressLineOne": "5775 Morehouse Drive, San Diego CA 92121",
"geoFenceCircle": {
"radius": 100,
"visibility": "ORGANIZATION",
"location": {
"latitude": 32.89494374592149,
"longitude": -117.19603832579497
}
},
"placeAttributes": {
"key1": "value1",
"key2": "value2"
}
},
{
"id": 3291
"name": "Gimbal R&D",
"addressLineOne": "5665 Morehouse Drive, San Diego CA 92121",
"geoFencePolygon": {
"visibility": "ORGANIZATION",
"locations": [
{
"latitude": 32.8953153522896,
"longitude": -117.19559844351653
},
{
"latitude": 32.8954009341414,
"longitude": -117.19516929007415
},
{
"latitude": 32.89564867061472,
"longitude": -117.1949815354431
},
{
"latitude": 32.89545949009762,
"longitude": -117.19463284827117
},
{
"latitude": 32.894986537037255,
"longitude": -117.19496544218902
},
{
"latitude": 32.894864920127866,
"longitude": -117.19554479933623
}
]
},
"placeAttributes": {
"key1": "value1",
"key2": "value2"
}
}]
这一切都很好,花花公子。但我的问题是我的代码,特别是这一行:
for geofence in geofences:
obj, created = Geofence.objects.get_or_create(name=geofence['name'])
我似乎提出了以下错误:
21:17:17 web.1 | obj, created = Geofence.objects.get_or_create(name=geofence['name'])
21:17:17 web.1 | TypeError: string indices must be integers
我无法弄清问题是什么,有人可以对此有所了解吗?
答案 0 :(得分:0)
最好检查地理围栏对象数据类型。
它看起来像是一个数组而不是地图。
答案 1 :(得分:0)
我认为您需要在名称索引前面放置一个索引。尝试:
obj, created = Geofence.objects.get_or_create(name=geofence[0]['name'])
答案 2 :(得分:0)
您的JSON格式的字符串数据已损坏(每个,
键后id
缺少两次):
[{
"id" : 1
"name" : "Gimbal HQ",
"addressLineOne" : "5775 Morehouse Drive, San Diego CA 92121"
}]
答案 3 :(得分:0)
我认为您正在将dict访问到列表中。
for geofence in geofences:
obj, created = Geofence.objects.get_or_create(name=geofence[geofence].get('name'))
这里['geofence']
指的是for循环的索引,它将选择列表对象并访问dict对象,你可以在python中编写get()
方法。这样做的主要好处是它将永远回归。