Home > front end >  Check value of nested json key
Check value of nested json key

Time:12-08

I would like to compare the value of a key from a JSON file to see if I have recorded data from todays date by seeing if the current date exists in the file so i don't record data from the same day. But this method seems to return False even if the date is present.

def removeJsonDupes(JSONcompleteFilePath, date):
    with open(JSONcompleteFilePath, "r") as file:
        dictionary = json.load(file)
        if dictionary.get("date") is str(date):
            dateRecorded = True
            print(date, "is in the dict")
        else:
            dateRecorded = False
            print(date, "is not in the dict")

return dateRecorded

JSON content:

{
     "prices": [
        {
            "date": "07/12/21",
            "prices": [
                "2.49",
                "1.61"
            ]
        }
    ]
}

CodePudding user response:

The dictionary.get() looks for keys and you only have the prices key. The key date is in the value of the prices key.

CodePudding user response:

Building on @TheFlyingObject's answer, the date key you are trying to retrieve is nested inside the dictionary.

In order to access it, you need to first get the key it is stored in (that is the prices key which holds a list) and then iterate over the objects in that list.

For example:

for i in dictionary['prices']:
    if i['date'] is str(date):
        print(date, 'is in the dict')
        return True
# we finished going over the list inside the prices key, and didn't find the date we were looking for
print(date, 'is not in the dict')
return False

CodePudding user response:

Change function as follows

def removeJsonDupes(JSONcompleteFilePath, date):
    with open(JSONcompleteFilePath, "r") as file:
        dictionary = json.load(file)
        if dictionary.get('prices')[0]['date'] is str(date): # condition changed
            dateRecorded = True
            print(date, "is in the dict")
        else:
            dateRecorded = False
            print(date, "is not in the dict")

    return dateRecorded

Will give following result

dictionary = {
     "prices": [
        {
            "date": "07/12/21",
            "prices": [
                "2.49",
                "1.61"
            ]
        }
    ]
}

removeJsonDupes(dictionary, "07/12/21")
# 07/12/21 is in the dict

removeJsonDupes(dictionary, "07/12/22")
# 07/12/22 is not in the dict
  • Related