复杂的Python JSON对象到自定义字典转换

复杂的Python JSON对象到自定义字典转换,第1张

概述我确实有以下 JSON对象 – { "Resource": [ { "@name": "Bravo", "@signature": "h#Bravo", "@type": "ESX_5.x", "@typeDisplayName": "ESX Server", 我确实有以下 JSON对象 –

{    "Resource": [        {            "@name": "Bravo","@signature": "h#Bravo","@type": "ESX_5.x","@typedisplayname": "ESX Server","PerfList": {                "@attrID": "cpuUsage","@attrname": "Usage","Data": [                    {                        "@data": "26.00","@end": "01:05:00","@interval": "60","@start": "01:04:00"                    },{                        "@data": "24.00","@end": "01:04:00","@start": "01:03:00"                    },{                        "@data": "36.00","@end": "01:03:00","@start": "01:02:00"                    },{                        "@data": "38.00","@end": "01:02:00","@start": "01:01:00"                    },{                        "@data": "37.00","@end": "01:01:00","@start": "01:00:00"                    }                ]            },"Resource": [                {                    "@name": "Tango","@signature": "vm#Tango","@type": "vm","@typedisplayname": "Virtual Machine","PerfList": {                        "@attrID": "cpuUsage","Data": {                            "@data": "12.00","@end": "04:05:00","@start": "04:04:00"                        }                    }                },{                    "@name": "CharlIE","@signature": "vm#CharlIE","Data": [                            {                                "@data": "12.00","@end": "04:20:00","@start": "04:19:00"                            },{                                "@data": "12.00","@end": "04:19:00","@start": "04:18:00"                            }                        ]                    }                }            ]        },{            "@name": "Alpha","@signature": "h#Alpha","PerfList": [                {                    "@attrID": "cpuUsage","Data": {                        "@data": "9","@end": "06:10:00","@start": "06:09:00"                    }                },{                    "@attrID": "cpuUsagemhz","@attrname": "Usage MHz","Data": {                        "@data": "479","@start": "06:09:00"                    }                }            ]        }    ]}

我正在寻找一些JsON遍历来达到所有键并将上面的转换为以下预期的python字典

d = { 'ESX_5.x' :         {             'Bravo' :                {                    "@typedisplayname" : "ESX Server","@signature" : "h#Bravo","cpuUsage" :                        {                            "from_01:04:00_to_01:05:00" : 26.00,"from_01:03:00_to_01:04:00" : 24.00,"from_01:02:00_to_01:03:00" : 36.00,"from_01:01:00_to_01:02:00" : 38.00,"from_01:00:00_to_01:01:00" : 37.00,"interval" : 60                        },"vm" :                        {                            "Tango" :                                {                                    "@typedisplayname" : "Virtual Machine","@signature" : "vm#Tango","cpuUsage" :                                        {                                            "from_04:04:00_to_04:05:00" : 12.00,"interval" : 60                                        }                                },"CharlIE" :                                {                                    "@typedisplayname" : "Virtual Machine","cpuUsage" :                                         {                                            "from_04:19:00_to_04:20:00" : "12.00","from_04:18:00_to_04:19:00" : "12.00",}                                }                        },},'Alpha' :                {                    "@typedisplayname" : "ESX Server","@signature" : "h#Alpha","cpuUsage" :                        {                            "from_06:09:00_to_06:10:00" : 9,"@interval": "60"                        },"cpuUsagemhz" :                        {                            "from_06:09:00_to_06:10:00" : 479,"@interval": "60"                        }                }        }    }

需要递归函数来获取资源和PerfList&数据和自定义词典.

手写熟的预期字典中可能存在拼写错误/ Syntax_errs …

这是我的代码所以 –
但是,对于N个嵌套资源,这是失败的.

import Jsonclass MQLPrettyPrint():    KEY_RESPONSE = 'Response'    KEY_RESulTS = 'Results'    KEY_RESOURCE = 'Resource'    def __init__(self,file=None):        self._Json_file = file        self._Json_data = self.read_Json_file()        self._Json_dict = self.Json_to_dict()    def Json_file(self):        return self._Json_file    def read_Json_file(self):        Json_data = ""        try:            JsON = open(self._Json_file,"r")            Json_data = JsON.read()            JsON.close()        except:            raise        return Json_data    def Json_to_dict(self):        return Json.loads(self._Json_data)    def Json_data(self):        return self._Json_data    def Json_dict(self):        return self._Json_dict    def Json2mql(self):        for key in self._Json_dict:            if key == self.KEY_RESPONSE:                val = self._Json_dict[key]                response = self.fetch_response(val)    def fetch_response(self,dict):        for key in dict:            if key == self.KEY_RESulTS:                val = dict[key]                results = self.fetch_results(val)    def fetch_results(self,dict):        for key in dict:            if key == self.KEY_RESOURCE:                val = dict[key]                resource = self.fetch_resource(val)    def fetch_resource(self,resources,dict={}):        if isinstance(resources,List):            for resource in resources:                print "\n\n",resource                if isinstance(resource,__builtins__.dict):                    #header = self.fetch_resource_header(resource)                    #perfList = self.fetch_perf_List(resource)                    self.fetch_resource(resource)        elif isinstance(resources,dict):            header = self.fetch_resource_header(resource)            perfList = self.fetch_perf_List(resource)        else:            print resources    def fetch_resouce_header(resource):        name = resource['@name']        signature = resource['@signature']        type = resource['@type']        typedisplayname = resource['@typedisplayname']        resource_dict = {'@name' : name,'@signature' : signature,'@type' : type,'@typedisplayname' : typedisplayname}        return resource_dict    def fetch_perf_List(self,resource,perfDict={}):        perfLists = resource['PerfList']        if isinstance(perfLists,List):            for perf in perfLists:                self.fetch_perf_List(perf,perfDict)        elif isinstance(perfLists,dict):            header = self.fetch_perf_header(perf)            dataList = self.fetch_data(perf)            key = ""            if len(perfDict) == 0:                key = header['@attrID']                perfDict[key] = header                perfDict[key]['Data'] = dataList            else:                if not perfDict.has_key(key):                    perfDict[key] = header                    perfDict[key]['Data'] = dataList                else:                    if perfDict.has_key('Data'):                        perfDict[key]['Data'].update(dataList)                    else:                        perfDict[key]['Data'] = dataList        else:            print perfLists        return perfDict    def fetch_perf_header(self,perfDict):        header = {}        attrID = perfDict['@attrID']        attrname = perfDict['@attrname']        header = {'@attrID' : attrID,'@attrname' : attrname}        return header    def fetch_data(self,perfDict,dataDict={}):        dataList = perfDict['Data']        if isinstance(dataList,List):            for data in dataList:                #Fetch internal data                self.fetch_data(data,dataDict)        elif isinstance(dataList,dict):            start = dataList['@start']            end = dataList['@end']            interval = dataList['@interval']            data = dataList['@data']            key = "%s_%s" % (start,end)            dataDict[key] = dataList            #data_dict = {key : dataList}            #if len(dataDict) == 0:            #    dataDict[key] = data_dict            #else:            #    dataDict['Data'].update(data_dict)        else:            print dataList        return dataDict
解决方法 有时,当使用递归函数在嵌套结构上 *** 作时,它更容易在行走函数和 *** 作函数方面进行思考.因此,我们希望定位Json结构中包含的所有dicts并对它们执行转换 *** 作.

在处理巢时,就地转换结构而不是重新创建新结构要容易得多.从Json结构构造嵌套dicts的更困难的方法是能够处理特定的Json元素,将它们放置在新结构的正确深度和分支处;这涉及两个平行的步行 *** 作.

但要注意的一件事是,在遍历它时修改嵌套结构,因为转换 *** 作可能会更改行走函数当前正在迭代的列表.在这种情况下,只有孩子(而不是兄弟姐妹)在走在较低的树枝上之前才会被修改.

from copy import deepcopyimport Jsonfrom pprint import pprintfrom StringIO import StringIOJson_str = \'''{    "Resource": [        {            "@name": "Bravo","@start": "06:09:00"                    }                }            ]        }    ]}'''def walk_fun_lim(iList,func=None):    '''    Recursively walk a nested List and dict structure,running func on all dicts    '''    def walk_fun_lim_helper(iList,func=None,count=0):        tList = []        ttList = []        if(isinstance(iList,List)):            ttList = filter(lambda x: x,func(filter(lambda x: isinstance(x,dict),iList)))            if(ttList):                tList += ttList            for q in iList:                ttList = filter(lambda x: x,walk_fun_lim_helper(q,func,count+1))                if(ttList):                    tList += ttList        elif(isinstance(iList,dict)):            ttList = filter(lambda x: x,func([iList]))            if(ttList):                tList += ttList            for q in iList:                ttList = filter(lambda x: x,walk_fun_lim_helper(iList[q],count+1))                if(ttList):                    tList += ttList        return [tList] if(count != 0) else tList    if(func != None and hasattr(func,"__call__")):        return walk_fun_lim_helper(iList,func)    else:        return []def transformers_robots_in_disguise(x):    for IDict in x:        pList = IDict.pop("PerfList",[])        pList = pList if(isinstance(pList,List)) else [pList]        for sub_dict in pList:            sub_name = sub_dict.pop("@attrID")            dList = sub_dict.pop("Data",[])            dList = dList if(isinstance(dList,List)) else [dList]            new_dict = {}            for sub_dict in dList:                new_dict["from_%(@start)s_to_%(@end)s" % sub_dict] = sub_dict["@data"]                new_dict["@interval"] = sub_dict["@interval"]            IDict[sub_name] = new_dict        rList = IDict.pop("Resource",[])        rList = rList if(isinstance(rList,List)) else [rList]        for sub_dict in rList:            sub_type = sub_dict.pop("@type")            sub_name = sub_dict.pop("@name")            IDict.setdefault(sub_type,{})[sub_name] = sub_dict    return []Json_data = Json.load(StringIO(Json_str))data_copy = deepcopy(Json_data)walk_fun_lim(data_copy,transformers_robots_in_disguise)pprint(data_copy)
总结

以上是内存溢出为你收集整理的复杂的Python JSON对象到自定义字典转换全部内容,希望文章能够帮你解决复杂的Python JSON对象到自定义字典转换所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1196864.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存