如何从这个json文件中获取信息?

时间:2016-12-16 22:18:22

标签: json python-2.7

我试图从这个json文件中获取一些数字,但我不知道如何正确地执行此操作。这是我试图收集信息的json文件:

http://stats.nba.com/stats/leaguedashteamstats?Conference=&DateFrom=&DateTo=&Division=&GameScope=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&PlusMinus=N&Rank=N&Season=2016-17&SeasonSegment=&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision=

我一直试图让这段代码发挥作用,但我无法弄清楚:

import json
from pprint import pprint

with open('data.json') as data_file:    
    data = json.load(data_file)


data["rowSet"] ["1610612737"] ["Atlanta Hawks"]

我试图从每个团队获取统计数据。

2 个答案:

答案 0 :(得分:0)

免责声明:此代码不包含任何验证,但它应引导您朝着正确的方向:

import json

with open('data.json') as data_file:    
    data = json.load(data_file)


for rs in data.get('resultSets'):
    for r_ in [r for r in rs.get('rowSet') if r[1] == 'Atlanta Hawks']:
        print(r_)

您基本上需要确定要循环或获取的特定键。

这应该有希望让你到达你需要的地方。

答案 1 :(得分:0)

以下Python脚本应该这样做。

#!/usr/bin/env python

import json

with open('leaguedashteamstats.json') as data_file:
    data = json.load(data_file)
    # extract headers names
    headers = data['resultSets'][0]['headers']

    # extract raw json rows
    raw_rows = data['resultSets'][0]['rowSet']

    team_stats = []
    for row in raw_rows:
        print row[1] # prints team name

        # mixes header names and values and prints them out
        for (header, value) in zip(headers, row):
            print header, value
        print '\n'

这里可以看到数据和代码: https://gist.github.com/cevaris/24d0b7d97677667aedb14059a6959da1#file-1-team-stats-output