键错误u';检查python字典中存储的JSON转储中的值时为True
我有一段代码,它从一个位置检索JSON转储,并检查存储字典中的值 我的JSON转储如下所示:键错误u';检查python字典中存储的JSON转储中的值时为True,python,json,dictionary,robotframework,keyerror,Python,Json,Dictionary,Robotframework,Keyerror,我有一段代码,它从一个位置检索JSON转储,并检查存储字典中的值 我的JSON转储如下所示: { u'response': { u'username': u'robo', u'first_name': u'robot-update', u'last_name': u'frmwrk-update', u'is_deleted': False, u'entity_type': u'user', u
{
u'response': {
u'username': u'robo',
u'first_name': u'robot-update',
u'last_name': u'frmwrk-update',
u'is_deleted': False,
u'entity_type': u'user',
u'admin': True,
u'image': {
u'complete_json': True,
u'entity_type': u'image',
u'original': u'/images/default-user-icon.png',
u'icon': u'/images/default-user-icon.png'
},
u'title': u'update-title',
u'email': u'robotupdate@robot.com',
u'dept': u'update-department',
u'subscribed_to_emails': True,
u'notes': u'update-note',
u'complete_json': True,
u'id': 177,
u'tags': [],
u'developer': True
}
}
我试图检索一个键值对,并将其与预期值进行比较
我的代码片段如下所示:user_info返回我的json转储:
def check_user_info(self, user_name, key_value, expected_value):
logger.info("Checking to see if the - {0} is the same as the expected value {1}...".format(field_value, expected_value))
user_info = self.my_api.get_user_info(self.token, self.app_address, user_name)
logger.console("json dumps------ {0}".format(user_info))
logger.console("the check value is-- {0}".format(user_info['response'][field_value]))
check_value = user_info['response'][field_value]
logger.info("field value is {0}".format(user_info['response'][field_value]))
if check_value == expected_value:
logger.info("The test value {0} is the same as expected value {1}".format(check_value, expected_value))
当我尝试查找名字、姓氏或电子邮件的值时。我通过了这个方法。但是当我尝试获取admin值时,我得到一个keyrerror u'True
请告诉我我做错了什么,因为您的代码在
字段值上引发了名称错误
,所以我认为这不是您的真实代码。现在考虑到您得到的错误,看起来您试图使用u'True'
作为key\u值
(这当然会产生KeyError
),而不是预期值
,调试的第一条规则是假设错误消息告诉您真相。在这种情况下,它告诉您keyrerror u'True
这意味着您在代码中的某个地方执行的操作相当于some\u dictionary[u'True']
。在您发布的代码中,没有使用文本值True
作为键,因此它必须位于变量中。由于您没有发布实际的错误,我不得不猜测是哪一行导致了错误
错误很可能来自以下代码:user\u info['response'][field\u value])
。这意味着字段\u值
很可能是u'True'
。现在的问题是,为什么这是真的?因为您的代码没有显示该值的来源,所以我无法回答这个问题。您必须在设置该变量的地方进行一些额外的调试
查看变量的名称,您似乎希望该变量包含一个值,但将其用作键。也许这就是问题所在?也许那行代码应该是user\u info['response'][user\u name]
(即:用user\u name
替换key\u value
) 我无法复制这个。你能扩展你的代码片段吗?user\u info=self.my\u api.get\u user\u info(self.token,self.app\u address,user\u name)Andy--请查看问题中编辑的代码。我已经给出了你的代码使用的全部方法,但是你没有设置任何地方。