如何搜索JSON数据流

3 投票
2 回答
11633 浏览
提问于 2025-04-16 22:46

我在使用下面的代码调用谷歌地图的API,并解析一些JSON数据。

def getLocalityFromPostCode(postcode):
    import urllib, json
    import pprint
    url = "http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" % postcode
    googleResponse = urllib.urlopen(url)
    jsonResponse = json.loads(googleResponse.read())
    return jsonResponse

这个方法运行得很好。不过,我只需要从['results']['address_components']中获取'type'[ "locality", "political" ]的值,但这个值的位置在不同的邮政编码字符串下会有所不同。

比如,如果我只输入一个简单的邮政编码(像XX10),这个值会出现在address_components列表的第0个位置。但是,如果我输入的是城市和邮政编码,它就会出现在第1个位置。

有人能帮我一下吗?我需要在address_components中查找[ "locality", "political" ]这个值。

编辑

你可以查看这些链接中的数据:http://maps.googleapis.com/maps/api/geocode/json?address=sy4&sensor=false(仅邮政编码)和http://maps.googleapis.com/maps/api/geocode/json?address=47%20High%20Street%20Shrewsbury,%20SY4&sensor=false(完整地址)。

从第一个例子中可以看到,我要找的数据在索引1,而在第二个例子中,我要找的数据在索引2。

2 个回答

-2

从json创建一个对象,并通过键来访问值

import json
obj = json.loads(jsonString)
7

这看起来正是你想要的 :)

results = json.load(googleResponse)['results']

for result in results:
    for address_component in result['address_components']:
        if address_component['types'] == ['locality', 'political']
            # address_component['long_name'] and
            # address_component['short_name'] are your data
            break

关于JSONPython字典,最酷的地方在于你不需要用数字来索引,而是用名字来索引。在这个例子中,你的对象(或者说你关心的数据)可以这样分解:

'results': # a list of resulting dicts
[
    { # one of those resulting dicts
        'address_components':  # a key, representing some other data
        [ # which, in this case, is a list of address component dicts
            { # like this
                'long_name': 'A String. The Long Name.'
                'short_name': 'Another String. The Short Name.'
                'types': # a list of type strings
                [
                    'locality', # one of the types
                    'political' # the other type
                ]
            }
        ]
    }
]

撰写回答