Pythonをはじめて学ぶと、JSONを読んで正しくデコードしています。最初のforループで名前をループすることができるので、名前の値を正しく取得しているとわかりました。その値を変数に設定しようとすると、次のエラーが発生します。Python変数を配列のdict値から設定していますか?
Traceback (most recent call last):
File "./logger.py", line 70, in <module>
winnerName = jsonData['players'][winner].get('name')
TypeError: list indices must be integers, not unicode
Pythonコード:
jsonData = json.load(open('file.json'))
## Functions correctly and prints each name out.
for i in range(0,7):
print jsonData['players'][i].get('name')
gameMatches = jsonData['games'][game]['matches']
for match in gameMatches:
winnerBool = 1
winner = -1
loser = -1
winnerName = ""
loserName = ""
matchCounter = 1
## Set the winner first then check to see who lost
for key, value in sorted(match.iteritems(), reverse=True):
if winnerBool:
winner = value
## This is where the error keeps pointing
winnerName = jsonData['players'][winner].get('name')
winnerBool = 0
elif winner != value:
loserName = jsonData['players'][loser].get('name')
loser = value
print winnerName
print loserName
JSONファイル:
{
"players":[
{"name":"Donatello","img":"\/img\/players\/1.jpg","rol":"\/img\/players\/r1.jpg"},
{"name":"Leonardo","img":"\/img\/players\/2.jpg","rol":"\/img\/players\/r2.jpg"},
{"name":"Michelangelo","img":"\/img\/players\/3.jpg","rol":"\/img\/players\/r3.jpg"},
{"name":"Raphael","img":"img\/players\/4.jpg","rol":"img\/players\/r4.jpg"},
{"name":"Shredder","img":"\/img\/players\/5.jpg","rol":"\/img\/players\/r5.jpg"},
{"name":"Rocksteady","img":"\/img\/players\/6.jpg","rol":"\/img\/players\/r6.jpg"},
{"name":"Bebop","img":"\/img\/players\/7.jpg","rol":"\/img\/players\/r7.jpg"},
{"name":"Foot Soldier","img":"\/img\/players\/8.jpg","rol":"\/img\/players\/r8.jpg"}
],
"games":[
{"matches":[
{"player1":"0","player2":"2","winner":"0"},
{"player1":"1","player2":"3","winner":"3"},
{"player1":"4","player2":"5","winner":"4"},
{"player1":"6","player2":"7","winner":"6"},
{"player1":"0","player2":"3","winner":"0"},
{"player1":"4","player2":"6","winner":"4"},
{"player1":"0","player2":"4","winner":"0"}
]
},
{"matches":[
{"player1":"0","player2":"2","winner":"2"},
{"player1":"1","player2":"3","winner":"3"},
{"player1":"4","player2":"5","winner":"4"},
{"player1":"6","player2":"7","winner":"7"},
{"player1":"2","player2":"3","winner":"2"},
{"player1":"4","player2":"7","winner":"4"},
{"player1":"2","player2":"4","winner":"4"}
]
}
]
}
あなたは完全なトレースバックを投稿してもらえますか?そして、完全な 'JSON'ファイルですか?あなたが投稿したものに '' games''セクションはありませんが、あなたのコードは '' jsonData ['games'] 'を参照しているからです。 – senderle
実際に正しいデータにアクセスしているかどうかを確認することなく、JSONには数値や文字列だけが含まれていません。だから勝者には文字列が含まれています。最初に番号に変換する必要があります。 –
「フットクラン」? 「フットソルジャー」を意味しないのですか? –