[英]strange TypeError: string indices must be integers
I have a strange problem parsing this json:我在解析这个 json 时遇到了一个奇怪的问题:
{
"status":"UP",
"diskSpace": {
"status":"UP",
"total":10434699264,
"free":8502456320,
"threshold":10485760
}
}
I'm usign the following call im my program:我正在使用以下调用我的程序:
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'])
I got the folowing output:我得到了以下 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
Why is python considering data[key]
as a string?为什么 python 将
data[key]
视为字符串?
I'm having troubles finding the issue.我很难找到问题。
Consider this code:考虑这段代码:
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')
which leads to this answer:这导致了这个答案:
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.