繁体   English   中英

奇怪的TypeError:字符串索引必须是整数

[英]strange TypeError: string indices must be integers

我在解析这个 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'])

我得到了以下 output:

$ 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

为什么 python 将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'>

暂无
暂无

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

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