检查嵌套 json 键的值

Check value of nested json key

我想比较 JSON 文件中的键值,通过查看文件中是否存在当前日期来查看我是否记录了今天的数据,因此我不记录数据从同一天开始。但是即使日期存在,这种方法似乎 return False。

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内容:

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

dictionary.get() 查找密钥,而您只有 prices 密钥。键 dateprices 键的值中。

基于@TheFlyingObject 的回答,您尝试检索的 date 键嵌套在字典中。

为了访问它,您需要首先获取存储它的键(即保存列表的 prices 键),然后遍历该列表中的对象。

例如:

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

改函数如下

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

将给出以下结果

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