从Python读取JSON对象导致TypeE

2024-05-15 16:41:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从Python读取JSON。以下是从地理代码请求返回的JSON对象:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Race Course Lane",
               "short_name" : "Race Course Ln",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Little India",
               "short_name" : "Little India",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Singapore",
               "short_name" : "Singapore",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Singapore",
               "short_name" : "SG",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Race Course Ln, Singapore",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 1.3103311,
                  "lng" : 103.85354
               },
               "southwest" : {
                  "lat" : 1.3091323,
                  "lng" : 103.8523656
               }
            },
            "location" : {
               "lat" : 1.3097033,
               "lng" : 103.8529918
            },
            "location_type" : "GEOMETRIC_CENTER",
            "viewport" : {
               "northeast" : {
                  "lat" : 1.311080680291502,
                  "lng" : 103.8543017802915
               },
               "southwest" : {
                  "lat" : 1.308382719708498,
                  "lng" : 103.8516038197085
               }
            }
         },
         "place_id" : "ChIJe5XzBMcZ2jERclOJt-xVp_o",
         "types" : [ "route" ]
      }
   ],
   "status" : "OK"
}

我试图得到格式化的地址和纬度lng下几何。这是我的密码:

json_data = requests.get(url).json()

formatted_address = json_data['results'][0]['formatted_address']
print(formatted_address)
for each in json_data['results'][0]['geometry']:
    print(each['lat'])

我设法打印出格式化的地址,但收到以下错误消息:

Traceback (most recent call last):
File "D:\Desktop\test.py", line 16, in <module>
print(each['lat'])

TypeError:字符串索引必须是整数

有什么想法吗?谢谢!你知道吗


Tags: namejsondataaddressresultslongtypesshort
1条回答
网友
1楼 · 发布于 2024-05-15 16:41:13

json_data['results'][0]['geometry']_dict_。这意味着,for x in json_data['results'][0]['geometry']将导致对键的迭代,其中x是分配给键(字符串)的循环变量。举个例子-

d = {'a' : 'b', 'c' : 'd'}

for each in d:
     print(x)   

a
c

因为each是一个字符串,each['lat']将是一个无效的操作(因为您不能用除整数之外的任何东西来索引字符串)


观察JSON文件的结构-

{
    "location_type": "GEOMETRIC_CENTER",
    ...

    "location": {
        "lng": 103.8529918,
        "lat": 1.3097033
    }
}

仔细观察,只有location具有与之相关联的latlng键的dict。如果您只需要这些值,那么只需直接索引它们。不需要循环

x = json_data['results'][0]['geometry']['location']
lat, lng = x['lat'], x['lng']

相关问题 更多 >