KeyError:'Bytes_Written'python

时间:2015-10-13 07:36:00

标签: python json

我不明白为什么我得到这个错误Bytes_Written在数据集中,但为什么python不能找到它?我从VM获取此信息(请参阅下面的数据集),我想选择Bytes_Written和Bytes_Read,然后从当前值中减去先前的值并打印 json对象,就像这样

{'Bytes_Written': previousValue-currentValue, 'Bytes_Read': previousValue-currentValue}

这是数据的样子:

  {
      "Number of Devices": 2,
      "Block Devices": {
        "bdev0": {
          "Backend_Device_Path": "/dev/disk/by-path/ip-192.168.26.1:3260-iscsi-iqn.2010-10.org.openstack:volume-d1c8e7c6-8c77-444c-9a93-8b56fa1e37f2-lun-010.0.0.142",
          "Capacity": "2147483648",
          "Guest_Device_Name": "vdb",
          "IO_Operations": "97069",
          "Bytes_Written": "34410496",
          "Bytes_Read": "363172864"
        },
        "bdev1": {
          "Backend_Device_Path": "/dev/disk/by-path/ip-192.168.26.1:3260-iscsi-iqn.2010-10.org.openstack:volume-b27110f9-41ba-4bc6-b97c-b5dde23af1f9-lun-010.0.0.146",
          "Capacity": "2147483648",
          "Guest_Device_Name": "vdb",
          "IO_Operations": "93",
          "Bytes_Written": "0",
          "Bytes_Read": "380928"
        }
      }
    }

这是我正在运行的完整代码。

 FIELDS = ("Bytes_Written", "Bytes_Read", "IO_Operation")


def counterVolume_one(state):
    url = 'http://url'
    r = requests.get(url)
    data = r.json()

    for field in FIELDS:
        state[field] += data[field]
    return state

state = {"Bytes_Written": 0, "Bytes_Read": 0, "IO_Operation": 0}
while True:
    counterVolume_one(state)
    time.sleep(1)
    for field in FIELDS:
        print("{field:s}: {count:d}".format(field=field, count=state[field]))

counterVolume_one(state)

1 个答案:

答案 0 :(得分:1)

您返回的JSON结构没有直接使用这些FIELDS = ("Bytes_Written", "Bytes_Read", "IO_Operation")个键。

您需要稍微修改一下代码。

data = r.json()

for block_device in data['Block Devices'].iterkeys():
    for field in FIELDS:
        state[field] += int(data['Block Devices'][block_device][field])