将请求内容写入CSV文件python代码
Write request content into CSV file python code
我正在使用以下代码从仪表板获取数据作为 json 文件:
ursl='https://xxxxxxxxx'
parameter = {
"access_token": 'ABCD',
"startDate":"2021-05-23",
"endDate":"2021-05-25",
"userId":'ERTI'
}
r = requests.get(url = ursl, params = parameter)
然后我将内容保存为 json 文件,然后将其写入 CSV 文件:
data=r.content
datajson=r.json()
# opening the csv file in 'w+' mode
file = open('DaTA.csv', 'w+')
# writing the data into the file
with file:
write = csv.writer(file)
write.writerow(datajson)
但我只在一个单元格中获取所有数据。 这是数据的快照:
{'date': {'_when': '2021-05-25', '_date': '2021-05-25T00:00:00.000Z'}, 'timeInterval': '1min', 'userId': '96K7D9', 'id': '60ac1401211c48001774aa3b', 'activities-heart': [{'customHeartRateZones': [], 'dateTime': '2021-05-25', 'heartRateZones': [{'caloriesOut': 993.8944, 'max': 115, 'min': 30, 'minutes': 1067, 'name': 'Out of Range'}, {'caloriesOut': 0, 'max': 142, 'min': 115, 'minutes': 0, 'name': 'Fat Burn'}, {'caloriesOut': 0, 'max': 175, 'min': 142, 'minutes': 0, 'name': 'Cardio'}, {'caloriesOut': 0, 'max': 220, 'min': 175, 'minutes': 0, 'name': 'Peak'}], 'value': '65.31'}], 'activities-heart-intraday':
{'dataset': [{'time': '00:45:00', 'value': 62}, {'time': '00:46:00', 'value': 61}, {'time': '00:47:00', 'value': 61}, {'time': '00:48:00', 'value': 59}, {'time': '00:49:00', 'value': 59}
你有什么建议吗,因为我希望数据是两列时间和值,从数据集单词开始。
我不确定 csv writer 是否允许您执行所需的操作而无需逐行循环。
也许改用 pandas
?
import pandas as pd
df = pd.DataFrame(datajson['activities-heart-intraday']['dataset'])
df.to_csv("data.csv", index=False)