从路径 python 中提取 Json 值



>我有一个示例 Json,其中包含键作为文件名和值作为文件路径。例如:

{
"sqlFiles":{
"sqlQueryPath": "tmp/r/test.sql"
},
"csvFiles": {
"firstSampleInput": "tmp/c/sample.csv",
"secondSampleInput": "tmp/c/sample1.csv"
}
}

我有一个函数,它将键作为输入,返回值作为输出。像这样:

def readFilePath(key):
with open('filePaths.json', 'r') as f:
config = json.load(f)
value = config[key]
return value

如果键可用作根元素,那么我的函数完全有效,但如果键以嵌套格式可用,就像它在 json 中可用一样,那么我的函数将失败。

我将使用 json 路径调用函数,如下所示:

readFilePath("sqlFiles.sqlQueryPath")

在函数中要进行哪些更改,它以格式解析路径config["sqlFiles"]["sqlQueryPath"]

这是一种方法。使用简单的迭代。

演示:

key = "sqlFiles.sqlQueryPath"
def readFilePath(key):
config = {
"sqlFiles":{
"sqlQueryPath": "tmp/r/test.sql"
},
"csvFiles": {
"firstSampleInput": "tmp/c/sample.csv",
"secondSampleInput": "tmp/c/sample1.csv"
}
}
for i in key.split("."):
if i in config:
config = config[i]
else:
return None

return config
print(readFilePath(key))

您需要将键拆分为"."并迭代读取值,pesudo 代码:

for nestedKey in key.split('.'): value = value[nestedKey]

你可以试试这个,

def readFilePath(key):
with open('filePaths.json', 'r') as f:
config = json.load(f)
value = ""
config_temp = config
try:
for k in key.split("."):
config_temp = config_temp[k]
value = config_temp
return value
except KeyError:
return value

您可以通过拆分输入并避免使用根键进行 for 循环来尝试此操作

def readFilePath(key):
json_keys = key.split('.')
with open('filePaths.json', 'r') as f:
config = json.load(f)
if len(json_keys) > 1:
value = config[json_keys[0]][json_keys[1]]
else:
value = config[json_keys[0]]
return value

这是一个解决方案:

def readFilePath(key):
with open("sample.json") as f:
config = json.load(f)
value = None
for k in key.split("."):
try:
value = config[k]
except KeyError:
config = value
return value[k]

最新更新