Python Forum

Full Version: Json filter is not capturing desired key/element
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I am trying to do the following:

1) Read the Json file (sample output attached).
2) If account ID is 4254254 AND "compliance": "Fail", I need to print the respective dictionary.

This is what I have done so far, but it is not working (error explained below):

import json

RAW_FILE = "to.json"
 
def scanvuln(file,account):

    # with open (file, 'r') as f:
    f = open(file, 'r')    
    data = json.load(f)
    for element in data:
        print(element)  #<== it does print the respective account that are in the json file. OK. 
        if data[account]["cloudformation"]["CloudFormation Drift Detection Analysis"]["analysis_results"][0]["compliance"] == "Fail":
                print(element) #<== This is simply not working. It does not capture the key/value. Goal is that if that if compliace== "Fail", I should print
                                      #the respective section of the dictionary for further analysis.
 
                                                                                                        
myaccount = "4254254"
scanvuln(RAW_FILE, myaccount)
Help is appreciated.
If you don't understand what your program is doing, always add print statements to see the progress in more detail. In this case you wonder why your "if" statement is not working. Just print the condition before the "if":
print(data[account]["cloudformation"]["CloudFormation Drift Detection Analysis"]["analysis_results"][0]["compliance"])
Output:
Pass
As "Pass" is not "Fail" nothing is printed.

Also it is strange you iterate over the elements (in your example there is only one element at toplevel) but you test always the same element: "data[account]". I think you want to test "data[element]".