首页 > 解决方案 > 查看JSON数据是否在文件中,如果没有,检查下一个文件

问题描述

例如,如何检查 JSON 数据是否在一个文件中,如果不在该文件中,请检查另一个文件

说这是“test.json”

{
"test":"test"
}

并说这是“base.json”

{
"base":"base"
}

假设我的程序中有一个名为 的变量EnabledJSONFiles,它看起来像这样 (Python): EnabledJSONFiles=['test.json', 'base.json']。该程序有一个用户提示搜索某些东西,并说用户搜索“base”,我当前的实现使用for i in range(len(EnabledJSONFiles)),但是当它在第一个 json 文件中找不到它时,它就崩溃了。那么如何解决这个问题以便检查下一个文件呢?

此外,它还会产生此错误

  File "/home/white/projects/pyjson.py", line 10, in handler
    for value in entry[argument]:
KeyError: 'test'

标签: pythonjsonpython-3.x

解决方案


对于您的循环,您似乎使用了错误的迭代类型,该range()函数返回索引,因此当您尝试打开文件时,它将尝试打开一个名为的文件,0然后是一个名为1etc 的文件(不存在)。由于您没有使用任何索引操作,我只会使用本机迭代语法。

像这样的东西:

import json

for json_file in EnabledJSONFiles:
    with open(json_file, "r") as open_file:
        content = json.load(open_file)
        ... # Check for values in file and break if it's found

如果您只想打印正确的文件,那么您可以将其变成一个函数,例如:

import json

def find_value_in_files(EnabledJSONFiles:list, value:str) -> str:
    for json_file in EnabledJSONFiles:
        with open(json_file, "r") as open_file:
            
            content = json.load(open_file)# Assuming the content is laid out exactly as it is in your example this will be a dictionary
            if content.get(value, False): # look for value and 
                return json_file
    return "" # Return an empty string if no file is found with the value

然后将使用以下方法调用它:

EnabledJSONFiles=['test.json', 'base.json']

print(find_value_in_files(EnabledJSONFiles, "base")) # Prints base.json

关于这种方法的说明

文件路径

我还注意到您的EnabledJSONFiles变量正在使用相对路径,请确保在编写此列表时文件实际转到正确的路径,并且这些文件存在。os.path.isfile()可以在您尝试打开文件之前告诉您文件是否存在,您可以根据您的用例选择此时要执行的操作。

JSON格式

读取 JSON 文件时,可以将它们读取为多种格式。如果文件的布局与您在示例中的编写方式完全相同,那么此建议将起作用,如果它们位于不同的模式中,则不会。例如,如果值在对象内部的对象中。像这样:

{
    "test": {
        "value": "value"
    }
}

推荐阅读