Python-访问JSON中的字段
我在访问JSON API中获得的某些字段时遇到问题,在API中,如果用户是多个on_调用策略的一部分,我不知道如何访问第二个或多个策略。我当前的代码只是在网络团队策略下返回Bob Brown两次,而不是在网络团队和solarwinds测试下返回Bob Brown两次 JSON示例Python-访问JSON中的字段,python,json,Python,Json,我在访问JSON API中获得的某些字段时遇到问题,在API中,如果用户是多个on_调用策略的一部分,我不知道如何访问第二个或多个策略。我当前的代码只是在网络团队策略下返回Bob Brown两次,而不是在网络团队和solarwinds测试下返回Bob Brown两次 JSON示例 { "users": [{ "id": "PN8PIFR", "name": "Bob Brown", "user_url": "/users/PN8PIFR",
{
"users": [{
"id": "PN8PIFR",
"name": "Bob Brown",
"user_url": "/users/PN8PIFR",
"invitation_sent": false,
"marketing_opt_out": false,
"on_call": [{
"level": 2,
"start": "2016-05-30T08:00:00Z",
"end": "2016-06-06T08:00:00Z",
"escalation_policy": {
"id": "PYZTEI3",
"name": "Network Team"
}
}, {
"level": 1,
"start": null,
"end": null,
"escalation_policy": {
"id": "P3CBIDO",
"name": "Solarwinds Test"
}
}],
"job_title": "Network Engineer"
}, {
"id": "PLIMHAI",
"name": "Bill Blue",
"user_url": "/users/PLIMHAI",
"invitation_sent": false,
"marketing_opt_out": false,
"on_call": [{
"level": 1,
"start": "2016-06-02T08:00:00Z",
"end": "2016-06-03T06:00:00Z",
"escalation_policy": {
"id": "PARVPQB",
"name": "DBA Team"
}
}],
"job_title": "Database Administrator"
}],
"active_account_users": 9,
"limit": 25,
"offset": 0,
"total": 6
}
view.py
class User(object):
__attrs = ['PolicyID','Level','LevelNo', 'StartDate', 'EndDate', 'StartTime',
'EndTime', 'Name', 'Mobile']
def __init__(self, **kwargs):
for attr in self.__attrs:
setattr(self, attr, kwargs.get(attr, None))
def __repr__(self):
return ', '.join(
['%s: %r' % (attr, getattr(self, attr)) for attr in self.__attrs])
### Get the Policy data ###
objPolicyData = getuser_data()
pdUsers = pdUser.objects.all()
### Index View ###
@login_required
def index(request):
OnCallData = []
for user_item_data in objPolicyData['users']:
user_data = User()
#get the user object from DB
model_pd_user = pdUser.objects.get(PagerDutyID=user_item_data['id'])
user_data.Name = model_pd_user.Name
user_data.Mobile = model_pd_user.Mobile
for on_call_data in user_item_data['on_call']:
user_data.LevelNo = on_call_data['level']
user_data.Level = getLevel(on_call_data['level'])
user_data.StartDate = getDate(on_call_data['start'])
user_data.EndDate = getDate(on_call_data['end'])
user_data.StartTime = getTime(on_call_data['start'])
user_data.EndTime = getTime(on_call_data['end'])
user_data.PolicyID = on_call_data['escalation_policy']['id']
OnCallData.append(user_data)
请包括您的异常/错误打印迭代中的值,我认为您正在以相同的方式覆盖object@JanvanderVegt这可能是正确的,因为您在开始循环
用户项目数据['on\u call']
之前创建了用户项目数据。你应该在每次迭代中创建一个新的,以防止出现这种情况。我认为这已经做到了!请包括您的异常/错误打印迭代中的值,我认为您正在以相同的方式覆盖object@JanvanderVegt这可能是正确的,因为您在开始循环用户项目数据['on\u call']
之前创建了用户项目数据。你应该在每次迭代中创建一个新的,以防止出现这种情况。我认为这已经做到了!