我对这个JSON有一个奇怪的问题:

{
    "status":"UP",
    "diskSpace": {
        "status":"UP",
        "total":10434699264,
        "free":8502456320,
        "threshold":10485760
    }
}

我在我的程序上签名如下:

import urllib.request, urllib.parse, urllib.error, ssl, json

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

# Retrieve data
# The context = ctx will ignore the errors from certificates
#url = 'https://www.google.com'
#html = urllib.request.urlopen(url, context=ctx).read()

with urllib.request.urlopen("url", context=ctx) as url:
    data = json.loads(url.read())
    mykey="diskSpace"
    print(data[mykey]['status'])
    for key in data:
        print(key)
        print(type(key))
        print(type(data))
        print(data[mykey]['status'])
        print(type(data[key]))
        print(data[key]['status'])

我拿到了这张照片:

$ python3 test.py
UP
status
<class 'str'>
<class 'dict'>
UP
<class 'str'>
Traceback (most recent call last):
  File "test.py", line 33, in <module>
    print(data[key]['status'])
TypeError: string indices must be integers

为什么巨蛇会考虑data[key] 作为一根绳子?

我在找问题。


想想这个代码:

data={
    "status":"UP",
    "diskSpace": {
        "status":"UP",
        "total":10434699264,
        "free":8502456320,
        "threshold":10485760
    }
}

for key in data:
    print('key=', key)
    print('data[key]=', data[key])
    print('type(data[key])=', type(data[key]))
    print('\n')

从而得出这个答案:

key= status
data[key]= UP
type(data[key])= <class 'str'>


key= diskSpace
data[key]= {'status': 'UP', 'total': 10434699264, 'free': 8502456320, 'threshold': 10485760}
type(data[key])= <class 'dict'>

很明显地data[key] 是一根绳子,所以data[key]['status'] 由于字符串索引不能是字符串,导致错误.

如果您将打印语句输出与打印语句放在一起作为注释,将会很有帮助。data[key] 是一根绳子而不是dict

抱歉,我找到了。在循环键的第一次迭代中=状态不是DITT。..