У меня есть сценарий, который выполняет вызов API и получает данные JSON с сотрудниками и их временные отметки в системе временных карт. Конечная цель состоит в том, чтобы проанализировать эти данные до того, что мне нужно, а затем вставить эти данные в таблицу SQL. Проблема в том, что у меня до сих пор генерируется желаемый результат только для одного сотрудника, а не для всех.
Я пробовал циклы и пытался создавать новые словари и т. Д., Но у каждого есть свои недостатки для того, чего я пытаюсь достичь.
Вот вывод JSON, который я пытаюсь проанализировать:
[
{
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"BreakMinutes": 0,
"DoubleTimeHours": 0.0,
"Duration": "07:00:00",
"Employee": {
"Email": "*************************",
"EmployeeId": null,
"FirstName": "Nicholas",
"FullName": "Nicholas ******",
"Id": 346186,
"IsActive": true,
"LastName": "******",
"Username": "*******"
},
"Hours": 7.0,
"Id": 13026137,
"JobCodeId": null,
"JobCodeName": "",
"LocationId": null,
"LocationName": "",
"OverTimeHours": 0.0,
"PTOEarningCodeAbbr": "",
"PTOEarningCodeId": null,
"PTOHours": null,
"PunchInApprovalStatusId": 4,
"PunchInApprovalStatusName": "Changed By Manager",
"PunchInDateTime": "2019-06-19T07:49:00",
"PunchInImageUrl": "",
"PunchInIpAddress": "*****",
"PunchInLatitude": null,
"PunchInLongitude": null,
"PunchInNotes": "",
"PunchOutApprovalStatusId": 4,
"PunchOutApprovalStatusName": "Changed By Manager",
"PunchOutDateTime": "2019-06-19T14:49:00",
"PunchOutImageUrl": "",
"PunchOutIpAddress": "****",
"PunchOutLatitude": null,
"PunchOutLongitude": null,
"PunchOutNotes": "",
"RegularHours": 7.0
}
]
[
{
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"BreakMinutes": 0,
"DoubleTimeHours": 0.0,
"Duration": "05:00:00",
"Employee": {
"Email": "********",
"EmployeeId": null,
"FirstName": "Test",
"FullName": "Test MBS",
"Id": 346188,
"IsActive": true,
"LastName": "MBS",
"Username": "testmbs"
},
"Hours": 5.0,
"Id": 13026141,
"JobCodeId": null,
"JobCodeName": "",
"LocationId": null,
"LocationName": "",
"OverTimeHours": 0.0,
"PTOEarningCodeAbbr": "",
"PTOEarningCodeId": null,
"PTOHours": null,
"PunchInApprovalStatusId": 4,
"PunchInApprovalStatusName": "Changed By Manager",
"PunchInDateTime": "2019-06-19T09:49:00",
"PunchInImageUrl": "",
"PunchInIpAddress": "****",
"PunchInLatitude": null,
"PunchInLongitude": null,
"PunchInNotes": "",
"PunchOutApprovalStatusId": 4,
"PunchOutApprovalStatusName": "Changed By Manager",
"PunchOutDateTime": "2019-06-19T14:49:00",
"PunchOutImageUrl": "",
"PunchOutIpAddress": "****",
"PunchOutLatitude": null,
"PunchOutLongitude": null,
"PunchOutNotes": "",
"RegularHours": 5.0
}
]
[
{
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"BreakMinutes": 0,
"DoubleTimeHours": 0.0,
"Duration": "05:00:00",
"Employee": {
"Email": "starlord@email.com",
"EmployeeId": "080097",
"FirstName": "Peter",
"FullName": "Peter Quill",
"Id": 346968,
"IsActive": true,
"LastName": "Quill",
"Username": "starlord"
},
"Hours": 5.0,
"Id": 12970292,
"JobCodeId": null,
"JobCodeName": "",
"LocationId": null,
"LocationName": "",
"OverTimeHours": 0.0,
"PTOEarningCodeAbbr": "",
"PTOEarningCodeId": null,
"PTOHours": null,
"PunchInApprovalStatusId": 4,
"PunchInApprovalStatusName": "Changed By Manager",
"PunchInDateTime": "2019-06-18T08:43:00",
"PunchInImageUrl": "",
"PunchInIpAddress": "****",
"PunchInLatitude": null,
"PunchInLongitude": null,
"PunchInNotes": "",
"PunchOutApprovalStatusId": 4,
"PunchOutApprovalStatusName": "Changed By Manager",
"PunchOutDateTime": "2019-06-18T13:43:00",
"PunchOutImageUrl": "",
"PunchOutIpAddress": "****",
"PunchOutLatitude": null,
"PunchOutLongitude": null,
"PunchOutNotes": "",
"RegularHours": 5.0
},
{
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"BreakMinutes": 0,
"DoubleTimeHours": 0.0,
"Duration": "01:16:00",
"Employee": {
"Email": "starlord@email.com",
"EmployeeId": "080097",
"FirstName": "Peter",
"FullName": "Peter Quill",
"Id": 346968,
"IsActive": true,
"LastName": "Quill",
"Username": "starlord"
},
"Hours": 1.267,
"Id": 12983841,
"JobCodeId": null,
"JobCodeName": "",
"LocationId": null,
"LocationName": "",
"OverTimeHours": 0.0,
"PTOEarningCodeAbbr": "",
"PTOEarningCodeId": null,
"PTOHours": null,
"PunchInApprovalStatusId": 4,
"PunchInApprovalStatusName": "Changed By Manager",
"PunchInDateTime": "2019-06-19T08:00:00",
"PunchInImageUrl": "",
"PunchInIpAddress": "****",
"PunchInLatitude": null,
"PunchInLongitude": null,
"PunchInNotes": "",
"PunchOutApprovalStatusId": 4,
"PunchOutApprovalStatusName": "Changed By Manager",
"PunchOutDateTime": "2019-06-19T09:16:00",
"PunchOutImageUrl": "",
"PunchOutIpAddress": "****",
"PunchOutLatitude": null,
"PunchOutLongitude": null,
"PunchOutNotes": "",
"RegularHours": 1.267
},
{
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"BreakMinutes": 0,
"DoubleTimeHours": 0.0,
"Duration": "03:00:00",
"Employee": {
"Email": "starlord@email.com",
"EmployeeId": "080097",
"FirstName": "Peter",
"FullName": "Peter Quill",
"Id": 346968,
"IsActive": true,
"LastName": "Quill",
"Username": "starlord"
},
"Hours": 3.0,
"Id": 13007880,
"JobCodeId": null,
"JobCodeName": "",
"LocationId": null,
"LocationName": "",
"OverTimeHours": 0.0,
"PTOEarningCodeAbbr": "",
"PTOEarningCodeId": null,
"PTOHours": null,
"PunchInApprovalStatusId": 4,
"PunchInApprovalStatusName": "Changed By Manager",
"PunchInDateTime": "2019-06-19T13:43:00",
"PunchInImageUrl": "",
"PunchInIpAddress": "****",
"PunchInLatitude": null,
"PunchInLongitude": null,
"PunchInNotes": "",
"PunchOutApprovalStatusId": 4,
"PunchOutApprovalStatusName": "Changed By Manager",
"PunchOutDateTime": "2019-06-19T16:43:00",
"PunchOutImageUrl": "",
"PunchOutIpAddress": "****",
"PunchOutLatitude": null,
"PunchOutLongitude": null,
"PunchOutNotes": "",
"RegularHours": 3.0
},
{
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"BreakMinutes": 0,
"DoubleTimeHours": 0.0,
"Duration": "04:00:00",
"Employee": {
"Email": "starlord@email.com",
"EmployeeId": "080097",
"FirstName": "Peter",
"FullName": "Peter Quill",
"Id": 346968,
"IsActive": true,
"LastName": "Quill",
"Username": "starlord"
},
"Hours": 4.0,
"Id": 13022834,
"JobCodeId": null,
"JobCodeName": "",
"LocationId": null,
"LocationName": "",
"OverTimeHours": 0.267,
"PTOEarningCodeAbbr": "",
"PTOEarningCodeId": null,
"PTOHours": null,
"PunchInApprovalStatusId": 4,
"PunchInApprovalStatusName": "Changed By Manager",
"PunchInDateTime": "2019-06-19T17:21:00",
"PunchInImageUrl": "",
"PunchInIpAddress": "****",
"PunchInLatitude": null,
"PunchInLongitude": null,
"PunchInNotes": "",
"PunchOutApprovalStatusId": 4,
"PunchOutApprovalStatusName": "Changed By Manager",
"PunchOutDateTime": "2019-06-19T21:21:00",
"PunchOutImageUrl": "",
"PunchOutIpAddress": "****",
"PunchOutLatitude": null,
"PunchOutLongitude": null,
"PunchOutNotes": "",
"RegularHours": 3.733
}
]
[
{
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"BreakMinutes": 0,
"DoubleTimeHours": 0.0,
"Duration": "15:33:00",
"Employee": {
"Email": "****",
"EmployeeId": "080098",
"FirstName": "Kelly",
"FullName": "Kelly ****",
"Id": 346187,
"IsActive": true,
"LastName": "****",
"Username": "****"
},
"Hours": 15.55,
"Id": 12963731,
"JobCodeId": 17673,
"JobCodeName": "Test dept 1",
"LocationId": null,
"LocationName": "",
"OverTimeHours": 0.0,
"PTOEarningCodeAbbr": "",
"PTOEarningCodeId": null,
"PTOHours": null,
"PunchInApprovalStatusId": 4,
"PunchInApprovalStatusName": "Changed By Manager",
"PunchInDateTime": "2019-06-18T08:27:00",
"PunchInImageUrl": "",
"PunchInIpAddress": "****",
"PunchInLatitude": null,
"PunchInLongitude": null,
"PunchInNotes": "",
"PunchOutApprovalStatusId": 2,
"PunchOutApprovalStatusName": "Approved",
"PunchOutDateTime": "2019-06-19T00:00:00",
"PunchOutImageUrl": "",
"PunchOutIpAddress": "****",
"PunchOutLatitude": null,
"PunchOutLongitude": null,
"PunchOutNotes": "",
"RegularHours": 15.55
},
{
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"BreakMinutes": 0,
"DoubleTimeHours": 0.0,
"Duration": "04:27:00",
"Employee": {
"Email": "****",
"EmployeeId": "080098",
"FirstName": "Kelly",
"FullName": "Kelly ****",
"Id": 346187,
"IsActive": true,
"LastName": "****",
"Username": "****"
},
"Hours": 4.45,
"Id": 12974763,
"JobCodeId": 17673,
"JobCodeName": "Test dept 1",
"LocationId": null,
"LocationName": "",
"OverTimeHours": 0.0,
"PTOEarningCodeAbbr": "",
"PTOEarningCodeId": null,
"PTOHours": null,
"PunchInApprovalStatusId": 4,
"PunchInApprovalStatusName": "Changed By Manager",
"PunchInDateTime": "2019-06-19T00:00:00",
"PunchInImageUrl": "",
"PunchInIpAddress": "****",
"PunchInLatitude": null,
"PunchInLongitude": null,
"PunchInNotes": "Shift automatically closed after 20 hours.",
"PunchOutApprovalStatusId": 2,
"PunchOutApprovalStatusName": "Approved",
"PunchOutDateTime": "2019-06-19T04:27:06.677",
"PunchOutImageUrl": "",
"PunchOutIpAddress": "****",
"PunchOutLatitude": null,
"PunchOutLongitude": null,
"PunchOutNotes": "Shift automatically closed after 20 hours.",
"RegularHours": 4.45
},
{
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"BreakMinutes": 0,
"DoubleTimeHours": 0.0,
"Duration": "05:00:00",
"Employee": {
"Email": "kellyw@marinercomputer.com",
"EmployeeId": "080098",
"FirstName": "Kelly",
"FullName": "Kelly ****",
"Id": 346187,
"IsActive": true,
"LastName": "****",
"Username": "****"
},
"Hours": 5.0,
"Id": 12980029,
"JobCodeId": null,
"JobCodeName": "",
"LocationId": null,
"LocationName": "",
"OverTimeHours": 0.0,
"PTOEarningCodeAbbr": "",
"PTOEarningCodeId": null,
"PTOHours": null,
"PunchInApprovalStatusId": 5,
"PunchInApprovalStatusName": "Time Recorded",
"PunchInDateTime": "2019-06-19T07:13:32.12",
"PunchInImageUrl": "",
"PunchInIpAddress": "****",
"PunchInLatitude": null,
"PunchInLongitude": null,
"PunchInNotes": "",
"PunchOutApprovalStatusId": 4,
"PunchOutApprovalStatusName": "Changed By Manager",
"PunchOutDateTime": "2019-06-19T12:13:00",
"PunchOutImageUrl": "",
"PunchOutIpAddress": "****",
"PunchOutLatitude": null,
"PunchOutLongitude": null,
"PunchOutNotes": "",
"RegularHours": 5.0
},
{
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"BreakMinutes": 0,
"DoubleTimeHours": 0.0,
"Duration": "10:00:00",
"Employee": {
"Email": "****",
"EmployeeId": "080098",
"FirstName": "Kelly",
"FullName": "Kelly ****",
"Id": 346187,
"IsActive": true,
"LastName": "****",
"Username": "****"
},
"Hours": 10.0,
"Id": 13064117,
"JobCodeId": null,
"JobCodeName": "",
"LocationId": null,
"LocationName": "",
"OverTimeHours": 0.0,
"PTOEarningCodeAbbr": "",
"PTOEarningCodeId": null,
"PTOHours": null,
"PunchInApprovalStatusId": 5,
"PunchInApprovalStatusName": "Time Recorded",
"PunchInDateTime": "2019-06-25T08:15:22.057",
"PunchInImageUrl": "",
"PunchInIpAddress": "****",
"PunchInLatitude": null,
"PunchInLongitude": null,
"PunchInNotes": "",
"PunchOutApprovalStatusId": 2,
"PunchOutApprovalStatusName": "Approved",
"PunchOutDateTime": "2019-06-25T18:15:00",
"PunchOutImageUrl": "",
"PunchOutIpAddress": "****",
"PunchOutLatitude": null,
"PunchOutLongitude": null,
"PunchOutNotes": "Shift automatically closed after 10 hours.",
"RegularHours": 10.0
},
{
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"BreakMinutes": 0,
"DoubleTimeHours": 0.0,
"Duration": null,
"Employee": {
"Email": "****",
"EmployeeId": "080098",
"FirstName": "Kelly",
"FullName": "Kelly ****",
"Id": 346187,
"IsActive": true,
"LastName": "****",
"Username": "****"
},
"Hours": null,
"Id": 13079310,
"JobCodeId": null,
"JobCodeName": "",
"LocationId": null,
"LocationName": "",
"OverTimeHours": 0.0,
"PTOEarningCodeAbbr": "",
"PTOEarningCodeId": null,
"PTOHours": null,
"PunchInApprovalStatusId": 5,
"PunchInApprovalStatusName": "Time Recorded",
"PunchInDateTime": "2019-06-26T06:32:03.1",
"PunchInImageUrl": "",
"PunchInIpAddress": "****",
"PunchInLatitude": null,
"PunchInLongitude": null,
"PunchInNotes": "",
"PunchOutApprovalStatusId": null,
"PunchOutApprovalStatusName": null,
"PunchOutDateTime": null,
"PunchOutImageUrl": "",
"PunchOutIpAddress": null,
"PunchOutLatitude": null,
"PunchOutLongitude": null,
"PunchOutNotes": "",
"RegularHours": 0.0
},
{
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"BreakMinutes": 0,
"DoubleTimeHours": 0.0,
"Duration": "09:30:00",
"Employee": {
"Email": "****",
"EmployeeId": "080098",
"FirstName": "Kelly",
"FullName": "Kelly ****",
"Id": 346187,
"IsActive": true,
"LastName": "****",
"Username": "****"
},
"Hours": 9.5,
"Id": 13084304,
"JobCodeId": null,
"JobCodeName": "",
"LocationId": null,
"LocationName": "",
"OverTimeHours": 0.0,
"PTOEarningCodeAbbr": "",
"PTOEarningCodeId": null,
"PTOHours": null,
"PunchInApprovalStatusId": 4,
"PunchInApprovalStatusName": "Changed By Manager",
"PunchInDateTime": "2019-06-21T06:30:00",
"PunchInImageUrl": "",
"PunchInIpAddress": "****",
"PunchInLatitude": null,
"PunchInLongitude": null,
"PunchInNotes": "",
"PunchOutApprovalStatusId": 4,
"PunchOutApprovalStatusName": "Changed By Manager",
"PunchOutDateTime": "2019-06-21T16:00:00",
"PunchOutImageUrl": "",
"PunchOutIpAddress": "****",
"PunchOutLatitude": null,
"PunchOutLongitude": null,
"PunchOutNotes": "",
"RegularHours": 9.5
}
]
Как вы можете видеть, это много данных, и это всего 4 сотрудника за 7 дней, что также потенциально может быть больше. Этот кусок json выводится этим кодом:
conn = httplib.HTTPSConnection('****.azure-api.net')
conn.request("GET", "/timecard/GetByPayPeriod/525117?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
tcdata = json.loads(data)
timecard_dict = {}
for timecard in tcdata:
tcid = timecard['Id']
timecard_dict.update({"Id": tcid})
for key in timecard_dict.keys():
id_no = str(timecard_dict['Id'])
tcurl = ("/time/timecard/" + id_no + "?%s")
conn = httplib.HTTPSConnection('****.azure-api.net')
conn.request("GET", tcurl % params, "{body}", headers)
response = conn.getresponse()
tcldata = response.read()
parsed = json.loads(tcldata)
print(json.dumps(parsed, indent=4, sort_keys=True))
Моя попытка просмотреть эти данные и получить нужные мне значения такова:
timepunches_dict = parsed
def employee_punch_data():
curr_date = None
for punch in timepunches_dict:
j = 1 if curr_date != punch['PunchInDateTime'][1:10] else j + 1
emp_id = punch['Employee']['EmployeeId']
emp_name = punch['Employee']['FullName']
curr_date = punch['PunchInDateTime'][1:10]
if punch['PunchInDateTime'] is not None:
punch_in_sql = punch['PunchInDateTime'].replace('T', ' ')
if punch['PunchOutDateTime'] is not None:
punch_out_sql = punch['PunchOutDateTime'].replace('T', ' ')
if today in punch_in_sql:
if j == 1:
print(emp_id, today, emp_name)
print(emp_id, today, j, punch_in_sql, punch_out_sql)
employee_punch_data()
Идея состоит в том, чтобы получить одну строку, содержащую данные, которые будут вставлены в таблицу заголовков, а затем каждый из их ударов в течение соответствующего дня в последовательности каждого ввода и вывода. Как и в первом наборе, это порядковый номер 1, а в следующем наборе - порядковый номер 2 и т. Д. В настоящее время мой вывод:
(u'080098', '2019-06-19', u'Kelly ****')
(u'080098', '2019-06-19', 1, u'2019-06-19 00:00:00', u'2019-06-19 04:27:06.677')
(u'080098', '2019-06-19', 2, u'2019-06-19 07:13:32.12', u'2019-06-19 12:13:00')
Но я надеялся получить:
(u'080098', '2019-06-19', u'Nicholas ****')
(u'080098', '2019-06-19', 1, u'2019-06-19 07:49:00', u'2019-06-19 14:49:00')
(u'080098', '2019-06-19', u'Test MBS')
(u'080098', '2019-06-19', 1, u'2019-06-19 09:49:00', u'2019-06-19 14:49:00')
(u'080098', '2019-06-19', u'Peter Quill')
(u'080098', '2019-06-19', 1, u'2019-06-19 08:00:00', u'2019-06-19 09:16:00')
(u'080098', '2019-06-19', 2, u'2019-06-19 13:43:00', u'2019-06-19 16:43:00')
(u'080098', '2019-06-19', 3, u'2019-06-19 17:21:00', u'2019-06-19 21:21:00')
(u'080098', '2019-06-19', u'Kelly ****')
(u'080098', '2019-06-19', 1, u'2019-06-19 00:00:00', u'2019-06-19 04:27:06.677')
(u'080098', '2019-06-19', 2, u'2019-06-19 07:13:32.12', u'2019-06-19 12:13:00')
По сути, вместо того, чтобы распечатывать эти значения, мой код будет вставлять их в базу данных sql, с которой я работал, мне просто нужно получить необходимые данные. Куда я иду не так? Я подозреваю, что я, возможно, перезаписываю данные и получаю только последний результат, или, возможно, мой цикл сбрасывается, чтобы начать заново с каждым сотрудником. Куда я здесь не так? Или, возможно, лучший вопрос, это вообще возможно? Должна ли функция работать внутри итеративного цикла? Извиняюсь за то, как долго этот пост стал.