Python「TypeError: string indices must be integers」のエラー原因と解決方法を紹介します。
結論
まず、出力されたエラーの内容を見てみましょう。
「TypeError: string indices must be integers」は、「文字列のインデックスはstring型ではなくint型でなければならない」という意味です。
このエラーが発生するサンプルプログラムを見てみます。
sample_str = 'sample'
print(sample_str[0]) # s
print(sample_str['s']) # TypeError: string indices must be integers
文字列sample_strに対してstring型のインデックスを指定しているためエラーが発生します。
よくある原因
想定外のJsonをパースしている
表題のエラーが発生する最も多い原因ではないでしょうか?
dictのkeyのつもりでオブジェクトを参照しているが、dictではなかった場合に発生します。
import json
expect_json = {"result":{"a":1}}
expect_json_str = json.dumps(expect_json)
unexpect_json = {"result":"a"}
unexpect_json_str = json.dumps(unexpect_json)
# key->"a"のvalue->1を参照
json_dict = json.loads(expect_json_str)
print(json_dict["result"]["a"]) # 1
# dictではないためエラー
json_dict = json.loads(unexpect_json_str)
print(json_dict["result"]["a"]) # TypeError: string indices must be integers
エラーが発生したときのチェックポイント
-
stringのインデックスはint型ですか?
-
dictを想定しているオブジェクトがstringになっていないか?
0 件のコメント :
コメントを投稿