I'm new in python and need get a value fron anoter value of same block, this is an example of 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'
}
I need get the value of Id from filed Name, eg. I need to know value of Id (test_pz4u6zug8swd2isfkcrzh9kjl) from Name 'test', is possible?
I get this JSON from a request:
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)
2 Answers 2
You can cycle through all your records and look for the first case where Name matches your desired value.
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)
answered Mar 15, 2018 at 22:57
SCB
6,1991 gold badge37 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
If the result is a list of dictionaries, you can use a comprehension to rearrange the data:
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
answered Mar 15, 2018 at 22:57
Norrius
7,9795 gold badges46 silver badges52 bronze badges
Comments
lang-py
[]from the example?json.loads. Which is fine, but your question needs to be clear. If you tell us you're giving one thing and instead give us something else, instead of the answers you need, you're going to get comments like the two above.