简体   繁体   中英

Python iterate over json response from requests in if/elif tree

I need to have my code go through a json response from requests along the lines of:

{
"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": []

}

I have if/elif code that needs to go through the response and look for each name field, and if it matches (in any order that may change each time the code grabs the JSON) any of what I'm looking for, grab the ID. I've managed to get it working with the first item in the list, but if there's any others it's ignored, even if I'm trying response[1][name] == 'www.islevel3down.com' and response[1]['type'] == 'A", it'll only return the first item. how do I make it go through the whole response?

my code is:

 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)

The reason you only get one and the others get ignored is because you end the function's execution with a return statement. Instead of returning, you can put the matching item in a list, and continue on looping over the response, like so:

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

Now you'll have all the matches in a list, instead of just the first one you find.

You are returning in the middle of your function. In addition you are trying to loop on the wrong values. Additionally, these stacked ifs create a lot of unneeded code. Suggest you try something more like:

Code:

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)

Test Code:

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)

Results:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM