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"
]
}
]
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With