在字典中提取特定的嵌套值

问题描述

对不起,如果我的措辞不正确。我没有python培训。

我请求了JSON,可以手动提取所需的数据。我知道有一种更好的方法来请求我想要的数据,并且一直在寻找正确的方向。

这就是我所拥有的(只要很长,我就只包含了JSON的一部分):

>   This is the example of the JSON that I am requesting.
  {"games": {
>       
>           "0":{
>     "id":"371749","gameUID":"1213028","sport":"Football","league":"NCAA","sportsbook":"Betonline","startDate":"2020-10-29T23:30:01Z","awayRotationNumber":"103","homeRotationNumber":"104","awayTeam":"South
> Alabama","homeTeam":"Georgia Southern","description":"South Alabama vs
> Georgia
> Southern","isLive":"0","gameMoneylineAwayPrice":"+165","gameMoneylineHomePrice":"-190","gameSpreadAwayHandicap":"+4","gameSpreadHomeHandicap":"-4","gameSpreadAwayPrice":"-110","gameSpreadHomePrice":"-110","gametotalPoints":"52","gametotaloverPrice":"-110","gametotalUnderPrice":"-110","gameTeamTotalAwayPoints":"24","gameTeamTotalAwayOverPrice":"-110","gameTeamTotalAwayUnderPrice":"-120","gameTeamTotalHomePoints":"28","gameTeamTotalHomeOverPrice":"-115","gameTeamTotalHomeUnderPrice":"-115","halfMoneylineAwayPrice":"+140","halfMoneylineHomePrice":"-160","halfSpreadAwayHandicap":"+3","halfSpreadHomeHandicap":"-3","halfSpreadAwayPrice":"-115","halfSpreadHomePrice":"-105","halfTotalPoints":"26","halfTotaloverPrice":"-115","halfTotalUnderPrice":"-105","periodMoneylineAwayPrice":"+135","periodMoneylineHomePrice":"-155","periodSpreadAwayHandicap":"+0.5","periodSpreadHomeHandicap":"-0.5","periodSpreadAwayPrice":"-105","periodSpreadHomePrice":"-115","periodTotalPoints":"10","periodTotaloverPrice":"-135","periodTotalUnderPrice":"+115","changedDate":"2020-10-29T14:31:16Z","checkedDate":"2020-10-29T15:13:33Z"}
>,"1":{(same as 0 etc etc...}

res = requests.get("myurl")

data = res.json()

game_one = data['games']['0']['awayTeam'] + " vs " + data['games']['0']['homeTeam'] + " " + data['games']['0']['gameSpreadHomeHandicap'] + "  "

game_two = data['games']['1']['awayTeam'] + " vs " + data['games']['1']['homeTeam'] + " " + data['games']['1']['gameSpreadHomeHandicap'] + "  "

game_three = data['games']['2']['awayTeam'] + " vs " + data['games']['2']['homeTeam'] + " " + 

ticker = game_one + game_two + game_three + game_four
output = open(r'E:\output.txt','w')
output.write(ticker)
output.close()

任何帮助将不胜感激。谢谢。

解决方法

尝试一下可能会起作用(如果您对代码有疑问,请询问他们):

games = []
for game in data['games']:
    for info in data['games'][game]:
        v1 = data['games'][game]['awayTeam'] + ' vs '
        v2 = data['games'][game]['homeTeam'] + ' '
        v3 = data['games'][game]['gameSpreadHomeHandicap']
    games.append(v1 + v2 + v3)
    
with open('yourfile.txt','w') as file:
    file.write(' '.join(games))