【问题标题】:Formatting httplib response (json)格式化 httplib 响应 (json)
【发布时间】:2015-04-30 13:18:38
【问题描述】:

经过一些研究,我能够通过 RESTful API 从网络设备获取数据:

if sys.version_info >= (2,7,9):
    import ssl
    conn = httplib.HTTPSConnection('192.168.158.136', 443, context=ssl._create_unverified_context())
else:
    conn = httplib.HTTPSConnection('192.168.158.136', 443)

headers = {"Authorization"  : "Basic %s" % base64.b64encode('user:pass'),
           "Content-Type"   : "application/json"}

url="https://192.168.158.136/wapi/v1.2/network?_return_fields%2b=extattrs"

conn.request('GET', url, headers=headers)
response = conn.getresponse()

print response.read()
conn.close()

这会打印出我需要的 json 格式的对象列表:

[
    {
        "_ref": "network/ZG5zLm5ldHdvcmskMTAuMC4wLjAvMjQvMA:10.0.0.0/24/default", 
        "extattrs": {
            "Location": {
                "value": "NAU"
            }
        }, 
        "network": "10.0.0.0/24", 
        "network_view": "default"
    }, 
    {
        "_ref": "network/ZG5zLm5ldHdvcmskMTAuMS4xLjAvMjQvMA:10.1.1.0/24/default", 
        "extattrs": {
            "Location": {
                "value": "BTN"
            }
        }, 
        "network": "10.1.1.0/24", 
        "network_view": "default"
    }, 
    {
        "_ref": "network/ZG5zLm5ldHdvcmskMTAuMi4yLjAvMjQvMA:10.2.2.0/24/default", 
        "extattrs": {
            "Location": {
                "value": "TRT"
            }
        }, 
        "network": "10.2.2.0/24", 
        "network_view": "default"
    }, 
    {
        "_ref": "network/ZG5zLm5ldHdvcmskMTkyLjE2OC4wLjAvMTYvMA:192.168.0.0/16/default", 
        "extattrs": {
            "Location": {
                "value": "MCW"
            }
        }, 
        "network": "192.168.0.0/16", 
        "network_view": "default"
    }
]

现在我需要“以某种方式”将其格式化为仅包含“网络”和extattrs“位置”的内容的列表(并且只有位置,会有其他的,但我只需要位置)格式为:

网络位置,即

10.0.0.0/24 NAU 10.1.1.0/24 BTN 10.2.2.0/24 TRT 192.168.0.0/16 MCW

我正在努力完成这项工作,即重新格式化我从查询中返回的 JSON 代码。

【问题讨论】:

  • 使用 json 模块将其转换为 python 数据结构。你会得到一个字典列表。遍历列表,打印出键 `network' 的值。
  • @ForceBru :感谢您的编辑,但“admin:infoblox”已经是一个虚拟密码,什么都不是
  • @AndreDieball,我没碰它。有another edit 影响了这个密码

标签: python json httplib


【解决方案1】:

您只需使用 json 模块即可将 JSON 数组解析为 dict。

import json

# Your code here

net_loc = []
resp_d = json.loads(response.read())
for obj in resp_d:
    net_loc.append(obj["network"] + " " + obj["extattrs"]["Location"]["value"])

net_loc 列表将包含您想要的内容。

【讨论】:

    【解决方案2】:

    在这里发布map 方法是有风险的,因为 SO 人们似乎不像map,但我会尝试一下:

    if sys.version_info >= (2,7,9):
        import ssl
        conn = httplib.HTTPSConnection('192.168.158.136', 443, context=ssl._create_unverified_context())
    else:
        conn = httplib.HTTPSConnection('192.168.158.136', 443)
    
    import json
    headers = {"Authorization"  : "Basic %s" % base64.b64encode('user:pass'),
               "Content-Type"   : "application/json"}
    
    url="https://192.168.158.136/wapi/v1.2/network?_return_fields%2b=extattrs"
    
    conn.request('GET', url, headers=headers)
    response = conn.getresponse()
    
    data = json.loads(response.read())
    conn.close()
    
    #variant 1. "map" approach
    networks = map(lambda x: "%s %s" % (x["network"], x["extattrs"]["Location"]["value"]), data)
    
    print("\n".join(networks))
    
    #variant 2. "for" approach
    networks = []
    for item in data:
      networks.append("%s %s" % (item["network"], item["extattrs"]["Location"])["value"]))
    
    print("\n".join(networks))
    

    【讨论】:

      猜你喜欢
      • 2014-01-21
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      相关资源
      最近更新 更多