我在将嵌套的json转换为数据框时遇到麻烦。我从API获取json,并希望将其放入数据框

时间:2019-09-26 13:53:53

标签: json python-3.x pandas api dataframe

此代码来自Sportradar API。 API将数据输出为JSON或XML;下面是我尝试使用JSON并将其放入数据框的尝试。

import numpy as np
import pandas as pd
import http.client
import json
from pandas.io.json import json_normalize

#API Call including my key
conn = http.client.HTTPSConnection("api.sportradar.us")

conn.request("GET", "/nfl/official/trial/v5/en/players/0acdcd3b-5442-4311-a139-ae7c506faf88/profile.json?api_key=99s3ewmn5rrdrd9r3v5wrfgd")
#conn.request("GET", "/nfl/official/trial/v5/en/games/b7aeb58f-7987-4202-bc41-3ad9a5b83fa4/pbp.json?api_key=99s3ewmn5rrdrd9r3v5wrfgd")
#conn.request("GET", "/nfl/official/trial/v5/en/teams/0d855753-ea21-4953-89f9-0e20aff9eb73/full_roster.json?api_key=99s3ewmn5rrdrd9r3v5wrfgd")
#conn.request("GET", "/nfl/official/trial/v5/en/games/030d37cf-b896-4f10-b16e-2a5120fef6cf/pbp.json?api_key=99s3ewmn5rrdrd9r3v5wrfgd")
res = conn.getresponse()
data = res.read()
data_dec = data.decode("utf-8")

json_data = json.loads(data_dec)
flat_data = json_normalize(json_data)

print(json_data)
df = pd.DataFrame.from_records(flat_data)
df2 = pd.DataFrame.from_dict(json_data, orient='index')
df2.reset_index(level=0, inplace=True)

#The closest thing to a dataframe I can get
df.head()

1 个答案:

答案 0 :(得分:0)

为什么不使用公开可用和维护的Python包装器。 参见link