检查嵌套JSON键的值。

3
我想比较从JSON文件中读取的键值是否存在当前日期,以此判断今天是否已经记录了数据,以避免重复记录。但是这种方法似乎无法返回True,即使日期存在也是如此。
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"
            ]
        }
    ]
}
3个回答

1

在@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

1
< p > dictionary.get() 方法寻找键,而你只有 prices 键。 date 键位于 prices 键对应的值中。


0

将函数更改如下

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接