如何解决展平对象的深层嵌套列表并创建一个csv怎么样?
'[
{
"match_id": "386491","match_hometeam_score": "3","match_awayteam_score": "1","statistics": [
{
"type": "Shots on Goal","home": "5","away": "5"
}
]
},{
"match_id": "386495","match_hometeam_score": "1","match_awayteam_score": "2","home": "10","away": "7"
}
]
}
]'
我想展平这个json响应。因为统计是对象列表,所以我很难做到。你能帮我这个忙吗?
到目前为止,我已经尝试过了
events_request = requests.get(events_url + api_key)
data = events_request.json()
data
df = pd.json_normalize(data,sep="_",record_path=[["statistics"]],)
然后我尝试了
json.dumps(data)
但是我所拥有的与我的期望无关。我期望的结果类似于这样的csv;
match_id,match_hometeam_score,match_awayteam_score,stattype,stathome,stataway
0,386491,3,1,Shots on goal,5,5
1,386495,2,10,7
解决方法
要获取所需的结构,您可以使用以下脚本(它将数据保存到data.csv
):
import json
import pandas as pd
data = '''[
{
"match_id": "386491","match_hometeam_score": "3","match_awayteam_score": "1","statistics": [
{
"type": "Shots on Goal","home": "5","away": "5"
}
]
},{
"match_id": "386495","match_hometeam_score": "1","match_awayteam_score": "2","home": "10","away": "7"
}
]
}
]'''
data = json.loads(data)
df = pd.json_normalize(data,'statistics',['match_id','match_hometeam_score','match_awayteam_score'])
df.to_csv('data.csv')
data.csv
的内容:
,type,home,away,match_id,match_hometeam_score,match_awayteam_score
0,Shots on Goal,5,386491,3,1
1,10,7,386495,1,2
LibreOffice的屏幕截图:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。