【问题标题】:How to search through a JSON feed如何搜索 JSON 提要
【发布时间】:2011-08-02 23:05:46
【问题描述】:

我正在使用下面的代码调用 Google Maps 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" ] 但是,该值的索引会根据给定的邮政编码字符串的精确程度而有所不同。

如果我给出一个直接的 poscode(如 XX10),则该值出现在 address_components 列表的第 0 项中。但是,如果我给出一个城市和邮政编码,它会出现在第一项中。

谁能帮帮我。我需要在 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 中看到的,我正在查找的数据在索引 1 中,而在第二个示例中,我正在查找的数据在索引 2 中。

【问题讨论】:

  • 你能在每种情况下发布一个 JSON 的例子吗?
  • 顺便说一句,使用requests.get('http://maps.googleapis.com/maps/api/geocode/json', {'address': '%s', 'sensor': 'false'}).json() 对我来说看起来更好。特别是如果您对属性使用单独的变量。 import requests 显然是必需的。

标签: python json google-maps


【解决方案1】:

这看起来像你想要的:)

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 dicts 最酷的地方在于,您不需要按数字索引,而是按名称索引。在这种情况下,您的对象(或至少您关心的数据)会像这样分解:

'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
                ]
            }
        ]
    }
]

【讨论】:

  • 我在读取for address_component in result['address_component']:的行上收到错误TypeError: string indices must be integers
  • 哎呀!我忽略了深入研究结果!现在修复:)
  • 我现在想好了。将result['address_component'] 更改为result['address_components'] 并将results 更改为googleResponse['results']
【解决方案2】:

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

import json
obj = json.loads(jsonString)

【讨论】:

  • 确认,不! JSON 不是 Python 的一个子集,无论如何您都不想在您的应用程序中评估其他人的东西。 json.loads(由 OP 使用)是获取对象的正确方法。问题是关于如何从对象本身访问数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 2017-01-23
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多