我是python中的新手,需要获得相同块的值,这是JSON的一个例子:
{
u'Name': u'test',
u'ProjectPath': u'/data/compose/test_pz4u6zug8swd2isfkcrzh9kjl',
u'ResourceControl': {
u'ResourceId': u'test',
u'UserAccesses': [
],
u'AdministratorsOnly': True,
u'TeamAccesses': [
],
u'SubResourceIds': [
],
u'Type': 6,
u'Id': 8
},
u'EntryPoint': u'docker-compose.yml',
u'Env': [
],
u'SwarmId': u'pz4u6zug8swd2isfkcrzh9kjl',
u'Id': u'test_pz4u6zug8swd2isfkcrzh9kjl'
},
{
u'Name': u'ycf',
u'ProjectPath': u'/data/compose/ycf_pz4u6zug8swd2isfkcrzh9kjl',
u'ResourceControl': {
u'ResourceId': u'ycf',
u'UserAccesses': [
],
u'AdministratorsOnly': True,
u'TeamAccesses': [
],
u'SubResourceIds': [
],
u'Type': 6,
u'Id': 5
},
u'EntryPoint': u'docker-compose.yml',
u'Env': None,
u'SwarmId': u'pz4u6zug8swd2isfkcrzh9kjl',
u'Id': u'ycf_pz4u6zug8swd2isfkcrzh9kjl'
}
我需要从提交的Id
获取Name
的值,例如。我需要知道来自Id
'test'的test_pz4u6zug8swd2isfkcrzh9kjl
(Name
)的价值,是否可能?
我从请求中获取此JSON:
r_get = requests.get(http://www.example.com:9000/api/endpoints/1/stacks)
id_response = json.loads(r_get.content.decode('utf-8'))
print(id_response)
答案 0 :(得分:3)
您可以循环浏览所有记录,并查找Name
符合您所需值的第一种情况。
for element in id_response:
if element[u'Name'] == u'test':
my_id = element[u'Id']
break
else:
# will only get here if we never break from the loop
raise ValueError('No element named "test"')
print(my_id)
答案 1 :(得分:1)
如果结果是字典列表,您可以使用理解来重新排列数据:
id_for_name = {item[u'Name']: item[u'Id'] for item in id_response}
print(id_for_name)
# {u'test': u'test_pz4u6zug8swd2isfkcrzh9kjl', u'ycf': u'ycf_pz4u6zug8swd2isfkcrzh9kjl'}
print(id_for_name['test'])
# test_pz4u6zug8swd2isfkcrzh9kjl