我对json
库的知识有些限制,但是我找不到任何地方访问文件分支的方法。我将使用http://json.org/example.html中的JSON示例文件来形成这个问题
{
"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"
}
}
}
}
}
我做了以下工作。 编写了预处理函数:
def PreProc(JSONFile):
with open(JSONFile, 'r') as myfile:
data = myfile.read()
myfile.close()
return data
并称之为:
path = 'C:\\path\\file.json'
Data = json.loads(PreProc(path))
此时:
print(type(Data.keys()))
print(Data.items())
print(type(Data.items()))
退货:
<class 'dict_keys'>
dict_items([('glossary', {'title': 'example glossary', 'GlossDiv': .......
<class 'dict_items'>
如何通过关键字访问JSON文件的任何分支或子分支,并以字符串或字典格式返回它?
我实际的JSON文件包含复杂对象的列表,这些对象中也包含对象的列表,这就是为什么我宁愿这样做,避免过于复杂的对象表示、jsondeconders和对象钩子,我就是绕不过去。
我正在寻找一种解决方案,其工作原理类似于以下概念函数:
def Recursion(Dict,Structure):
#Attempts to find a keyword that marks the begging of a complex ctructure in a given dictionary
try:
for key in Dict.keys():
#Parses through all the keys of the dictionary
try:
if key==Structure:
NewDict = key.items()
return NewDict
else:
#Set the dictionary that will be used in the recursion as all the items in the 'key' branch
dict = key.items()
Recursion(dict, Structure)
except:
continue
except:
print("Needed Structure Not Found in Dictionary ", Dict, " !")
函数的调用抛出和AttributeError
,因为在第一个递归步骤中,它试图将dict_items
解析为dict
。理想情况下,声明:
BranchedData = Recursion(Data,'GlossList')
print(BranchedData)
应输出(作为字符串或dict):
{
"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"
}
}
编辑:澄清问题,调整代码,以保持清晰和错误
目前没有回答
相关问题 更多 >
编程相关推荐