簡體   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