4

I am trying to extract/parse the values from specifics in a JSON file that I did a post request.

Here is the JSON File. I am trying to get the values from the Key "AN". I want to be able to extract values such as "shannoncampbell_znyq1", "katiekapprelmac", etc. such that the values from the second row does not equal to the number zero. For example, since the second row values (the for this row is T7) of katiekapprelmac does not equal to zero, my code should spit that out (katiekapprelmac should be the output). However it does not.

JSON File:

{
"id": "jsonrpc",
"jsonrpc": "2.0",
"result": {
    "result": [
        {
            "AccountId": 697429,
            "Flags": [
                "AutoDeployed"
            ],
            "PartnerId": 287562,
            "Settings": [
                {
                    "AN": "shannoncampbell_znyq1"
                },
                {
                    "T7": "0"
                }
            ]
        },
        {
            "AccountId": 725177,
            "Flags": null,
            "PartnerId": 287562,
            "Settings": [
                {
                    "AN": "katiekapprelmac"
                },
                {
                    "T7": "5"
                }
            ]
        },
        {
            "AccountId": 689130,
            "Flags": [
                "AutoDeployed"
            ],
            "PartnerId": 287562,
            "Settings": [
                {
                    "AN": "sara-pc_wpv7h"
                },
                {
                    "T7": "0"
                }
            ]
        },
        {
            "AccountId": 697531,
            "Flags": null,
            "PartnerId": 287562,
            "Settings": [
                {
                    "AN": "kaelaweeksmac"
                },
                {
                    "T7": "0"
                }
            ]
        },
        {
            "AccountId": 615877,
            "Flags": null,
            "PartnerId": 249098,
            "Settings": [
                {
                    "AN": "elenimacbookpro"
                },
                {
                    "T7": "0"
                }
            ]
        },
        {
            "AccountId": 700661,
            "Flags": null,
            "PartnerId": 287562,
            "Settings": [
                {
                    "AN": "sethnickersonmac"
                },
                {
                    "T7": "0"
                }
            ]
        },

Here is my python code:

response2 = requests.request("POST", url, data=payload2, headers=headers)

j = json.loads(response2.text) 


def find_all(item, level):
    if isinstance(item, dict):
        for k in item:
            (find_all(item[k], level+1))
    else:
        print(item)


def find_only(item, level):
    if isinstance(item, dict):
        for k in item:
            (find_only(item[k], level+1))


for each in j['result']['result']:
    if (find_only(each['Settings'][1], 0)) != json.loads("0"):
        find_all(each['Settings'][0], 0)

Instead, I get all the keys in the output. I get the following:

shannoncampbell_znyq1
katiekapprelmac
sara-pc_wpv7h
kaelaweeksmac
elenimacbookpro
sethnickersonmac

Rather than just katiekapprelmac

Please help. Thanks

gordon sung
  • 605
  • 2
  • 8
  • 27
  • 1
    Possible duplicate of [recursive iteration through nested json for specific key in python](https://stackoverflow.com/questions/21028979/recursive-iteration-through-nested-json-for-specific-key-in-python) – Maurice Meyer Jan 13 '19 at 23:54

2 Answers2

2

In the code:

for each in j['result']['result']:
if (find_only(each['Settings'][1], 0)) != json.loads("0"):
    find_all(each['Settings'][0], 0)

I actually see, your condition is always True, as you are not returning anything in find_only().

I don't know, why you are using level and so many recursive function. Although it's easy to extract result as per your data posted. please find below code.

response2 = requests.request("POST", url, data=payload2, headers=headers)
j = json.loads(response2.text)
for each in j['result']['result']:
if each['Settings'][1]['T7'] not in ["0", 0]:
    print(each['Settings'][0]['AN'])

If your response data is little complex then please post for exact solution.

If you have multiple key name then please look at below code:

response2 = requests.request("POST", url, data=payload2, headers=headers)
j = json.loads(response2.text)

def find_all(item):
    if isinstance(item, dict):
        for k in item:
            return item[k]
    # If item is non dict and you want to return this as well on `True`.
    # Uncomment below commented lines.
    # else:
    #     item
def find_only(item):
    if isinstance(item, dict):
        for k in item:
            return item[k]

for each in j['result']['result']:
    if (find_only(each['Settings'][1])) != str(json.loads("0")):
        print(find_all(each['Settings'][0]))
1

jsonpath-ng can help you with this.

from jsonpath_ng.ext import parse

found = parse(f"$..Settings").find(data)
if found:
    for i in found:
        if ''.join(i.value[1].values()) != '0':
            print(i.value[0]['AN'])
Frans
  • 799
  • 6
  • 7