gpt4 book ai didi

python - 检查嵌套 json 键的值

转载 作者:行者123 更新时间:2023-12-05 04:40:26 24 4
gpt4 key购买 nike

我想通过查看当前日期是否存在于文件中来比较 JSON 文件中的键值,以查看我是否记录了今天的数据,因此我不记录同一天的数据。但是即使日期存在,此方法似乎也返回 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"
]
}
]
}

最佳答案

基于@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

关于python - 检查嵌套 json 键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70271601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com