から値を取得できません。私が現在取り組んでいる現在の対応については、私は特定の価値をつかむことができません。は、私は、データのクラスでこのメソッドを持っているPythonの辞書
通常、私は
status, resp = submit_request("GET", "/path/to/...", body)
info = json.loads(resp)
value = info["value"]
を行くだろうと私は辞書からその対応する値を使用するように設定されます。しかし、私が下に示すように、私はこのケースのためにそれを行うことができません。私はコピーして、この応答をPASE場合
>>> print resp
[{"deviceId":28,"displayName":"test-device","status":"Pending_Authorized"}]
私は
>>> resp[0]['deviceId']
28
を行うことができますが、コードの中でそれを行うと、(私はちょうどresp[0]
から[
を取得)は動作しません。私は続ける
TypeError: string indices must be integers, not str
これはなぜ起こっているのか?
ここに関連するコードです:
def test_get_device_list(self):
'''
GET /Device/List
'''
status_code, resp = self.api.submit_request("GET", "/Device/List")
log.log_info("GET /Device/List: HTTP - %s" % str(status_code))
log.log_info("GET /Device/List: Response - %s" % str(resp))
self.assertEqual(status_code, 200)
#GET /Device/{DeviceID}
device_id = self.api.parse_header(resp, "deviceId")
status_get, resp_get = self.api.submit_request("GET", "/Device/%s" % str(device_id))
log.log_info("GET /Device/{DeviceID}: HTTP - %s" % str(status_get))
log.log_info("GET /Device/{DeviceID}: Response - %s" % str(resp_get))
self.assertEqual(status_get, 200)
とサポートするデータクラスから
def submit_request(self, method, path, body=None, header=None):
conn = httplib.HTTPSConnection(self.host)
conn.request(method, path, body, self.headers)
resp = conn.getresponse()
return resp.status, resp.read()
def parse_header(self, resp, arg):
info = json.loads(resp)
parse = info["%s" % str(arg)]
return parse
ここで完全なエラーです:
ERROR: test_get_device_list (__main__.TestAPI)
----------------------------------------------------------------------
Traceback (most recent call last):
File "API.py", line 207, in test_get_device_list
device_id = self.api.parse_header(str(resp), "deviceId")
File "/home/zach/Desktop/Automation/data.py", line 47, in parse_header
parse = info["%s" % str(arg)]
TypeError: list indices must be integers, not str
私はへの道を見つけようとしているが、上記の 'deviceId'を応答から取り出します。私はparse_header()メソッドで異なる応答でそれをやっていましたが、この応答では動作しません。
あなたは、単一のオブジェクトを含む配列である応答オブジェクトを変数 'info'にロードしてから、その配列の' value "プロパティにアクセスしようとしています。配列には "値"のプロパティはありません。 – Hamms
だから、なぜあなたの 'resp'文字列に' json.loads'を使わなかったのですか? – user2357112
@ user2357112私は同じタイプエラー – user3239567