我正在读取一个JSON文件,用我的extract_json函数检索一些值并通过time_minutes_coords = extract_json("boxes", "time_minutes", "coord")
调用它,这为我的coord值提供了正确的路径。
def extract_json(one,two,three):
with open('document.json') as data_file:
data = json.load(data_file)
return data[one][two][three]
但它适用于3个参数。如果我想将此函数用于传递的任意数量的参数,该怎么办?我希望有类似的东西:
def extract_json(*args):
with open('document.json') as data_file:
data = json.load(data_file)
return data[args]
但所有的args都以这种方式显示:
(args1,args2,args3,args4)
和data(args1, args2, args3, args4)
什么都不返回。我怎么能有这样的东西:
数据[args1] [args2] [args3] [args4]
是否在json文件中移动到正确的值?
答案 0 :(得分:0)
您可以通过jsonpath-rw
module使用 JSONPath 解决此问题。工作样本:
from jsonpath_rw import parse
obj = {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
keys = ["glossary", "GlossDiv", "GlossList", "GlossEntry", "GlossDef", "para"]
jsonpath_expr = parse(".".join(keys))
print(jsonpath_expr.find(obj)[0].value)
打印:
A meta-markup language, used to create markup languages such as DocBook.
这里的密钥以列表的形式出现(在您的情况下是args
)。然后,密钥与dot
连接以构建到所需节点的路径。