Python迭代来自if / elif树中的请求的json响应

时间:2018-02-05 00:00:29

标签: python json python-requests

我需要让我的代码通过以下行的请求来完成json响应:

{
"result": [
    {
        "id": "59c190c075529ad185ea03affa8842b6",
        "type": "A",
        "name": "islevel3down.com",
        "content": "45.76.20.24",
        "proxiable": true,
        "proxied": false,
        "ttl": 1,
        "locked": false,
        "zone_id": "1163722f4a43f5bbee9af23c2f4c4c68",
        "zone_name": "islevel3down.com",
        "modified_on": "2017-12-15T17:03:11.560689Z",
        "created_on": "2017-12-15T17:03:11.560689Z",
        "meta": {
            "auto_added": false,
            "managed_by_apps": false
        }
    },
    {
        "id": "25073fc3caaa457918aadf6da68b2dac",
        "type": "A",
        "name": "www.islevel3down.com",
        "content": "45.76.20.24",
        "proxiable": true,
        "proxied": false,
        "ttl": 1,
        "locked": false,
        "zone_id": "1163722f4a43f5bbee9af23c2f4c4c68",
        "zone_name": "islevel3down.com",
        "modified_on": "2017-12-15T17:03:09.922229Z",
        "created_on": "2017-12-15T17:03:09.922229Z",
        "meta": {
            "auto_added": false,
            "managed_by_apps": false
        }
    },
    {
        "id": "961392b581639d41d0a044f6709763aa",
        "type": "TXT",
        "name": "islevel3down.com",
        "content": "keybase-site-verification=blah",
        "proxiable": false,
        "proxied": false,
        "ttl": 1,
        "locked": false,
        "zone_id": "1163722f4a43f5bbee9af23c2f4c4c68",
        "zone_name": "islevel3down.com",
        "modified_on": "2017-11-29T00:55:01.555837Z",
        "created_on": "2017-11-29T00:55:01.555837Z",
        "meta": {
            "auto_added": false,
            "managed_by_apps": false
        }
    }
],
"result_info": {
    "page": 1,
    "per_page": 20,
    "total_pages": 1,
    "count": 3,
    "total_count": 3
},
"success": true,
"errors": [],
"messages": []

}

我有if / elif代码需要通过响应并查找每个名称字段,如果它匹配(以任何顺序,每次代码可以更改JSON),我的任何一个寻找,抓住ID。我设法让它与列表中的第一个项目一起工作,但如果有其他任何其他项目被忽略,即使我正在尝试     回复[1] [姓名] ==' www.islevel3down.com'和响应[1] ['类型'] ==' A",它只返回第一个项目。如何让它完成整个回复?

我的代码是:

 from variables import *
 import requests
 import json
 def RecordsExist(zone, CLOUDFLARE_EMAIL, CLOUDFLARE_AUTH_KEY, 
islevel3down.com, www.islevel3down.com):
url = "https://api.cloudflare.com/client/v4/zones/" + zone + 
"/dns_records"
headers = {
    'X-Auth-Email': CLOUDFLARE_EMAIL,
    'X-Auth-Key': CLOUDFLARE_AUTH_KEY,
    'Cache-Control': "no-cache"
}

r = requests.request("GET", url, headers=headers)
response = r.json()
print(response)
print("From Response")
for response in response['result']:
    print(response)
    print("first")

    for r in response:
        print(r)
        if response['name'] == 'islevel3down.com' and 
 response['type'] == 'A':
            ipv4Exists = True
            ipv4Zone = response['id']
            if ipv4Zone != '':
                print('ipv4 =' + ipv4Zone)
                return ipv4Zone
            else:
                ipv4Zone = False
                return ipv4Zone


        if response[1]['name'] == 'www.islevel3down.com' and response[1]['type'] == 'A':
            ipv4wwwExists = True
            ipv4wwwZone = response[1]['id']
            print("Lol")

            if ipv4wwwZone != '':
                print("ipv4www =" +ipv4wwwZone)
                return ipv4wwwZone
            else:
                ipv4wwwZone = False
                return ipv4wwwZone

        if response[2]['name'] == 'islevel3down.com' and response[2]['type'] == 'AAAA':
            ipv6Exists = True
            ipv6Zone = response[2]['id']
            if ipv6Zone != '':
                print('ipv6 =' + ipv6Zone)
                return ipv6Zone
            else:
                ipv6Zone = False
                return ipv6Zone
        if response[3]['name'] == 'www.islevel3down.com' and response[3]['type'] == 'AAAA':
            ipv6wwwExists = True
            ipv6wwwZone = response[3]['id']
            if ipv6wwwZone != '':
                print('ipv6www =' + ipv6wwwZone)
                return ipv6wwwZone
            else:
                ipv6wwwZone = False
                return ipv6wwwZone
test = RecordsExist(zone, CLOUDFLARE_EMAIL, CLOUDFLARE_AUTH_KEY, islevel3down.com, www.islevel3down.com)

2 个答案:

答案 0 :(得分:1)

你只得到一个而其他人被忽略的原因是因为你用return语句结束了函数的执行。您可以将匹配项放在列表中,然后继续循环响应,而不是返回,如下所示:

def record():
    matches = []
    response = json.load(open("js"))
    for r in response['result']:
        if r['name'] == 'islevel3down.com' and r['type'] == 'A':
            ipv4Exists = True
            ipv4Zone = r['id']
            if ipv4Zone != '':
                print('ipv4 =' + ipv4Zone)
            else:
                ipv4Zone = False
            matches.append(ipv4Zone)

    return matches

现在,您将列出所有匹配项,而不仅仅是您找到的第一个匹配项。

答案 1 :(得分:0)

您正在功能中间返回。此外,您正试图循环错误的值。此外,这些堆叠的ifs会产生大量不必要的代码。建议你尝试更像:

代码:

lookup = (
    ('islevel3down.com', 'A', 'ipv4'),
    ('www.islevel3down.com', 'A', 'ipv4-www'),
    ('islevel3down.com', 'AAAA', 'ipv6'),
    ('www.islevel3down.com', 'AAAA', 'ipv6-www'),
)

zones = {}
for r in response['result']:
    for l in lookup:
        if r['name'] == l[0] and r['type'] == l[1] and r['id']:
            zones[l[2]] = r['id']
print(zones)

测试代码:

import json
response = json.loads("""
{
    "result": [
        {
            "id": "59c190c075529ad185ea03affa8842b6",
            "type": "A",
            "name": "islevel3down.com",
            "content": "45.76.20.24",
            "proxiable": true,
            "proxied": false,
            "ttl": 1,
            "locked": false,
            "zone_id": "1163722f4a43f5bbee9af23c2f4c4c68",
            "zone_name": "islevel3down.com",
            "modified_on": "2017-12-15T17:03:11.560689Z",
            "created_on": "2017-12-15T17:03:11.560689Z",
            "meta": {
                "auto_added": false,
                "managed_by_apps": false
            }
        },
        {
            "id": "25073fc3caaa457918aadf6da68b2dac",
            "type": "A",
            "name": "www.islevel3down.com",
            "content": "45.76.20.24",
            "proxiable": true,
            "proxied": false,
            "ttl": 1,
            "locked": false,
            "zone_id": "1163722f4a43f5bbee9af23c2f4c4c68",
            "zone_name": "islevel3down.com",
            "modified_on": "2017-12-15T17:03:09.922229Z",
            "created_on": "2017-12-15T17:03:09.922229Z",
            "meta": {
                "auto_added": false,
                "managed_by_apps": false
            }
        },
        {
            "id": "961392b581639d41d0a044f6709763aa",
            "type": "TXT",
            "name": "islevel3down.com",
            "content": "keybase-site-verification=blah",
            "proxiable": false,
            "proxied": false,
            "ttl": 1,
            "locked": false,
            "zone_id": "1163722f4a43f5bbee9af23c2f4c4c68",
            "zone_name": "islevel3down.com",
            "modified_on": "2017-11-29T00:55:01.555837Z",
            "created_on": "2017-11-29T00:55:01.555837Z",
            "meta": {
                "auto_added": false,
                "managed_by_apps": false
            }
        }
    ],
    "result_info": {
        "page": 1,
        "per_page": 20,
        "total_pages": 1,
        "count": 3,
        "total_count": 3
    },
    "success": true,
    "errors": [],
    "messages": []
    }
""")


lookup = (
    ('islevel3down.com', 'A', 'ipv4'),
    ('www.islevel3down.com', 'A', 'ipv4-www'),
    ('islevel3down.com', 'AAAA', 'ipv6'),
    ('www.islevel3down.com', 'AAAA', 'ipv6-www'),
)

zones = {}
for r in response['result']:
    for l in lookup:
        if r['name'] == l[0] and r['type'] == l[1] and r['id']:
            zones[l[2]] = r['id']
print(zones)

结果:

{
    'ipv4': '59c190c075529ad185ea03affa8842b6',
    'ipv4-www': '25073fc3caaa457918aadf6da68b2dac'
}