Creating lists and dictionaries from JSON data in Python

This question already has an answer here:

  • Parsing values from a JSON file? 7 answers

  • from_this = {"version":"0.0","response":[{"macAddress":"88:5A:92:A4:E7:C8","networkDeviceId":"e15789bd-47df-4df9-809f-daf81d15ff2a","lineCardId":"e5bddd56-2194-4b83-8ae5-597893800051","lastUpdated":"2014-06-03 01:39:19.855491-07","platformId":"C897VA-K9","vendor":"Cisco","numUpdates":1,"interfaceCount":"10","portRange":"ATM0, ATM0.1, BRI0, BRI0:1-2, Dialer1, Ethernet0, GigabitEthernet0-8, LISP0, Loopback0-1, NVI0, Virtual-Access1, Virtual-Template1, Vlan1","roleSource":"auto","chassisType":"C800","softwareVersion":"15.4(2)T","upTime":"2 weeks, 3 days, 18 hours, 2 minutes","imageName":"c800-universalk9-mz.SPA.154-2.T.bin","memorySize":"988236K/60339K","managementIpAddress":"192.168.2.1","family":"C897VA-K9","type":"UNKNOWN","serialNumber":"FGL175124DX","role":"Unknown","hostname":"chaney-xtr"}, {"macAddress":"88:5A:92:A4:E7:C8","networkDeviceId":"e15789bd-47df-4df9-809f-daf81d15ff2a","lineCardId":"e5bddd56-2194-4b83-8ae5-597893800051","lastUpdated":"2014-06-03 01:39:19.855491-07","platformId":"C897VA-K9","vendor":"Cisco","numUpdates":1,"interfaceCount":"10","portRange":"ATM0, ATM0.1, BRI0, BRI0:1-2, Dialer1, Ethernet0, GigabitEthernet0-8, LISP0, Loopback0-1, NVI0, Virtual-Access1, Virtual-Template1, Vlan1","roleSource":"auto","chassisType":"C800","softwareVersion":"15.4(2)T","upTime":"2 weeks, 3 days, 18 hours, 2 minutes","imageName":"c800-universalk9-mz.SPA.154-2.T.bin","memorySize":"988236K/60339K","managementIpAddress":"192.168.2.2","family":"C897VA-K9","type":"UNKNOWN","serialNumber":"XGL175124D3","role":"Unknown","hostname":"chaney-xtr2"}]}
    
    dict1 = {}
    dict2 = {}
    
    for response_item in from_this['response']:
        dict1[response_item['managementIpAddress']] = response_item['hostname']
        dict2[response_item['managementIpAddress']] = response_item['platformId']
    

    The output looks like this:

    In[189]: dict1
    Out[187]: {'192.168.2.1': 'chaney-xtr', '192.168.2.2': 'chaney-xtr2'}
    In[190]: dict2
    Out[188]: {'192.168.2.1': 'C897VA-K9', '192.168.2.2': 'C897VA-K9'}
    

    If this is what you were looking for, let me know if you have any questions.


    你可以解析JSON数据,然后添加一些if和else的情况来判断是否需要数据;然后使用eval语句来伪造一个字典

    链接地址: http://www.djcxy.com/p/38044.html

    上一篇: 使用Python如何将JSON转换为数组列表

    下一篇: 在Python中从JSON数据创建列表和词典