2

我在动态创建 Python 字典路径以循环并验证值时遇到问题。这是我想做的:

使用 Requests 1.0 进行 API 调用并将 JSON 响应存储在字典中。

response = requests.get(path/to/file.json).json()

响应对象的格式如下:

{   
"status": "OK",
"items": [
    {
        "name": "Name 1",
        "id": 0,
        "address":{
            "city": "New York",
        }
    },
    {
        "name": "Name 2",
        "id": 1,
        "address":{
            "city": "New York",
        }
    },
    {
        "name": "Name 3",
        "id": 2,
        "address":{
            "city": "New York",
        }
    }]
}

响应字典、字段发送到函数进行验证。该函数将获取响应对象并将字段条目附加到它以定义其路径,然后根据该值进行验证。所以理论上它会是:

response[field] = value

我为此编写的代码是:

def dynamic_assertion(response, field, value):
        i = 0
        stations = "response['items']"
        count = len(response['items'])
        while i < count:
            path = '%s[%s]%s' % (stations, i, field)
            path = path.strip("")
            if path != value:
                print type(path)
                return False
            i += 1
        return True

dynamic_assertion(response, "['address']['city']", "New York")

我意识到,一旦我创建了路径字符串,它就不再是一个对象。如何以允许我保留响应对象并附加引用路径以遍历的方式创建它?这甚至可能吗?

4

1 回答 1

1

我认为您最好避免使用单个path字符串,而使用表示嵌套字典中各个键的元组或字符串列表。也就是说,您不会"['address']['city']"成为您的field论点,而是通过("address", "city"). 然后你只需要一个循环来遍历键并查看最终值是否正确:

def dynamic_assertion(response, field, value):
    for item in response["items"]:
        for key in field:
            item = item[key] # go deeper into the nested dictionary
        if item != value:
            return False # raising an exception might be more Pythonic
    return True

示例输出(给定response问题中的字典):

>>> dynamic_assertion(response, ("address", "city"), "New York")
True
>>> dynamic_assertion(response, ("address", "city"), "Boston")
False
>>> response["items"][2]["address"]["city"] = "Boston" # make response invalid 
>>> dynamic_assertion(response, ("address", "city"), "New York")
False
>>> dynamic_assertion(response, ("address", "city"), "Boston")
False
于 2012-12-21T01:48:18.537 回答