json.loads()的分支加载字典作为新字典

时间:2018-01-12 23:30:53

标签: python json string dictionary

我对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文件包含复杂对象的列表,这些对象也包含其中的对象列表,这就是为什么我宁愿这样做,并避免过于复杂的对象表示和JSONDecoders和对象挂钩,我无法绕过我的脑袋。 我正在寻找一种有点像这个概念功能的解决方案:

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)

应输出(作为字符串或字典):

{
    "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"
    }
}  

编辑:澄清问题并调整代码以获得清晰和愚蠢的错误

0 个答案:

没有答案