python - 检查嵌套 json 键的值

标签 python json dictionary key-value

我想通过查看当前日期是否存在于文件中来比较 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/

相关文章:

javascript - pdf生成后重定向

python - Django 模型中的外键

python - 在 Android 上使用 bash shell 打开浏览器后尝试输入搜索数据

php - Ajax 实时搜索框

c++ - 字典访问优化描述 - 它发生在任何地方吗?

c++ - 如何为指针引用定义 SWIG 类型映射?

javascript - 使用 YQL 和 MooTools 进行 Json 请求

json - 如何将 JSON 字符串转换为 BSONDocument

python访问字典中字典中的元素

python - 为什么我无法打印返回值?