问题描述
我有一个示例Json,其中包含键作为fileName和值作为filepath。 例如:
{
"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"]
格式解析路径的函数需要进行哪些更改
1楼
这是一种方法。 使用简单的迭代。
演示:
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))
2楼
您需要用“。”分隔键。 并迭代读取值,伪代码:
for nestedKey in key.split('.'): value = value[nestedKey]
3楼
您可以通过拆分输入并使用根键避免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
4楼
你可以试试看
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
5楼
这是一个解决方案:
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]