【问题标题】:Return/obtain values from json if keypair matches - Python如果密钥对匹配,则从 json 返回/获取值 - Python
【发布时间】:2021-03-12 04:32:21
【问题描述】:

目前,我可以使用其 api 从网站中提取硬盘状态列表。 我想精简我的结果,并从我的结果中返回密钥对“status”:“Degraded”或“status”:“Pred Fail”的数据。

这是没有任何解析的 json 的样子:

{
  "results": [
    {
      "bytesPerSector": 512,
      "description": "SSD",
      "interfaceType": "RAID",
      "manufacturer": "UNKNOWN",
      "mediaType": "Fixed hard disk media",
      "model": "OEM Genuine 500GB",
      "name": "\\\\.\\PHYSICALDRIVE0",
      "partitionCount": 1,
      "serialNumber": "Notputting that in here",
      "size": 500105249280,
      "smartCapable": true,
      "status": "OK",
      "deviceId": taking this out as well,
      "timestamp": 1573080987.0
    },

目前,我已将结果精简为仅显示 ['interfaceType'],['manufacturer'],['model'],['status'];但是,我只想提取具有 ['status':'Degraded'] 或 ['status':'Pred Fail'] 作为硬盘驱动器状态的部分。 (如果这有意义?)

这是我目前的代码:

alerts = ''
for i in range (len(napialert['results'])):
    ninjainterfaceType_str = json.dumps(napialert['results'][i]['interfaceType'], indent=2,)
    ninjamanufacturer_str = json.dumps(napialert['results'][i]['manufacturer'], indent=2,)
    ninjamodel = json.dumps(napialert['results'][i]['model'], indent=2,)
    ninjastatus = json.dumps(napialert['results'][i]['status'], indent=2,)
    alerts += (ninjainterfaceType_str + "\n" + ninjamanufacturer_str + "\n" + ninjamodel + "\n" + ninjastatus + "\n _____________________________\n")
    
print("Here are a list of Hard drive with manufacturer problems: " + alerts)

这是结果(但它会打印所有结果,而不仅仅是那些有故障状态的结果):

Here are a list of Hard drive with manufacturer problems: "RAID"
"UNKNOWN"
"OEM Genuine 500GB"
"OK"
 _____________________________
"SATA"
"Western Digital"
"WDC WD1502FAEX-007BA0"
"OK"
 _____________________________
"SATA"
"UNKNOWN"
"ADATA SP550"
"OK"

More below this...

如果有人有任何想法或建议可以尝试,请告诉我。

【问题讨论】:

    标签: python json for-loop parsing


    【解决方案1】:

    你没有做任何事情来实际检查状态...?

    您的for 循环也很奇怪;因为您不关心列表中有多少项或当前项的索引,所以只需遍历项目本身,而不是列表索引的范围。

    for res in napialert['results']:
        if res['status'] in ('Degraded', 'Pred Fail'):
            for attr in ('interfaceType', 'manufacturer', 'model', 'status'):
                print(res[attr])
    

    我也认为没有理由将字符串收集到一个列表中,并且仅在我们基本上将程序的内存消耗增加一倍(不,等待,三倍)时才打印。找到匹配项后立即打印,然后继续下一个。将每个单独的字符串转换回 JSON(即有效地在其周围添加双引号)的怪异舞蹈似乎也是多余的,但如果它确实增加了价值,当然很容易放回去。

    【讨论】:

    • 这完全适合我!我将您的答案作为正确答案,因为它更有效。我只是在学习 python,所以就效率而言,我的技术很糟糕,但我将它放入字符串的原因是因为我将使用 tkinter 使应用程序图形化。所以我有一些"n\" + "__________" + "n\" 让它在 tkinter 中看起来更好。可能有比这更好的方法,但我会尽快研究。再次感谢您。
    【解决方案2】:

    我看到了几个潜在的问题,第一个可能是你得到的 json 对象的格式,它可能需要被剥离,也许你的 API 实际上是正确返回的,如果这是案例只是对状态属性进行实际检查,您可以在下面找到一个示例,使用数组并检查当前对象的状态是否在该数组中:

    import json
    
    napialert = {
      "results": [
        {
          "bytesPerSector": 512,
          "description": "SSD",
          "interfaceType": "RAID",
          "manufacturer": "UNKNOWN",
          "mediaType": "Fixed hard disk media",
          "model": "OEM Genuine 500GB",
          "name": "\\\\.\\PHYSICALDRIVE0",
          "partitionCount": 1,
          "serialNumber": "Notputting that in here",
          "size": 500105249280,
          "smartCapable": True,
          "status": "OK",
          "deviceId": "taking this out as well",
          "timestamp": 1573080987.0
        },
            {
          "bytesPerSector": 512,
          "description": "SSD",
          "interfaceType": "RAID",
          "manufacturer": "UNKNOWN",
          "mediaType": "Fixed hard disk media",
          "model": "OEM Genuine 500GB",
          "name": "\\\\.\\PHYSICALDRIVE0",
          "partitionCount": 1,
          "serialNumber": "Notputting that in here",
          "size": 500105249280,
          "smartCapable": True,
          "status": "Degraded",
          "deviceId": "taking this out as well",
          "timestamp": 1573080987.0
        },
            {
          "bytesPerSector": 512,
          "description": "SSD",
          "interfaceType": "RAID",
          "manufacturer": "UNKNOWN",
          "mediaType": "Fixed hard disk media",
          "model": "OEM Genuine 500GB",
          "name": "\\\\.\\PHYSICALDRIVE0",
          "partitionCount": 1,
          "serialNumber": "Notputting that in here",
          "size": 500105249280,
          "smartCapable": True,
          "status": "Pred Fail",
          "deviceId": "taking this out as well",
          "timestamp": 1573080987.0
        }
        ]
    }
    
    alerts = ''
    checks = ["Pred Fail", "Degraded"]
    for i in range (len(napialert['results'])):
        status = json.dumps(napialert['results'][i]['status'])
        if status.strip('"') in checks:
            ninjainterfaceType_str = json.dumps(napialert['results'][i]['interfaceType'], indent=2,)
            ninjamanufacturer_str = json.dumps(napialert['results'][i]['manufacturer'], indent=2,)
            ninjamodel = json.dumps(napialert['results'][i]['model'], indent=2,)
            ninjastatus = json.dumps(napialert['results'][i]['status'], indent=2,)
            alerts += (ninjainterfaceType_str + "\n" + ninjamanufacturer_str + "\n" + ninjamodel + "\n" + ninjastatus + "\n _____________________________\n")
        
    print("Here are a list of Hard drive with manufacturer problems: " + alerts)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-20
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多