简体   繁体   English

如果密钥对匹配,则从 json 返回/获取值 - Python

[英]Return/obtain values from json if keypair matches - Python

Currently I am able to pull a list of hard drive statuses from a website using its api.目前,我可以使用其 api 从网站中提取硬盘驱动器状态列表。 I want to slim down my results and have return back the data that the key pair "status": "Degraded", or "status": "Pred Fail" from my result.我想缩小我的结果,并从我的结果中返回密钥对“status”:“Degraded”或“status”:“Pred Fail”的数据。

Here is what the json looks like without any parsing:这是 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
    },

Currently, I have slimmed down my results to only show ['interfaceType'],['manufacturer'],['model'],['status'];目前,我已将结果精简为仅显示 ['interfaceType'],['manufacturer'],['model'],['status']; however, I only want to pull the sections that have ['status':'Degraded'] or ['status':'Pred Fail'] as their status for the hard drive.但是,我只想提取具有 ['status':'Degraded'] 或 ['status':'Pred Fail'] 作为硬盘驱动器状态的部分。 (If that make sense?) (如果这有意义?)

Here is the code I have so far:这是我到目前为止的代码:

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 the results (but it prints all of them instead of just the ones that have a failure status):以下是结果(但它会打印所有结果,而不仅仅是那些有故障状态的结果):

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...

Let me know if anyone has any ideas or suggestions to try.让我知道是否有人有任何想法或建议可以尝试。

You are doing nothing to actually examine the status...?你没有做任何事情来实际检查状态......?

Your for loop is also weird;for循环也很奇怪; since you don't care how many items there are or the index of the current one within the list, just loop over the items themselves, instead of the range of list indices.因为您不关心列表中有多少项目或当前项目的索引,所以只需遍历项目本身,而不是列表索引的范围。

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

I could also see no reason to collect the strings into a list and only print when we have basically doubled (no, wait, tripled) the program's memory consumption.我也认为没有理由将字符串收集到列表中,并且仅在我们基本上将程序的 memory 消耗量增加一倍(不,等待,三倍)时才打印。 Just print as soon as you find a match, and move on to the next one.找到匹配项后立即打印,然后继续下一个。 The weird dance to convert each individual string back to JSON (ie effectively add double quotes around it) also seemed superfluous, but will of course be easy to put back in if it actually adds value.将每个单独的字符串转换回 JSON (即有效地在其周围添加双引号)的奇怪舞蹈似乎也是多余的,但如果它确实增加了价值,当然很容易放回去。

I see a couple of potential issues, the first one might be with the format of the json object you are getting it has '"' that might need to get stripped, maybe your API is actually returning this correctly, if that's the case is just matter of doing an actual check on the status property, you can find an example below, using an array and checking if the status of the current object is in that array:我看到了几个潜在的问题,第一个可能是 json object 的格式,你得到它有 '"' 可能需要被剥离,也许你的 API 只是正确返回这个,关于对 status 属性进行实际检查的问题,您可以在下面找到一个示例,使用数组并检查当前 object 的状态是否在该数组中:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM