-1

I have this data set:

print(resp)

{'entityId': 'Vcenter-123', 
'displayName': 'testVCenter', 
'firstSeenTms': 1584129386246, 
'lastSeenTms': 1625163328453, 
'properties': {'virtualizationSupervisor': 'VMWARE_VCENTER', 'detectedName': 'testVCenter', 'vcenterHostNumber': 60, 'vcenterVmNumber': 1612, 'vcenterInfo': '[vendor: VMware, Inc., version: 6.5.0, host: testVCenter]'}, 
'tags': [], 
'managementZones': [{'id': '0001234', 'name': 'test123'}], 
'icon': {'primaryIconType': 'vcenter'}, 'fromRelationships': {'manages': [{'id': 'HYPERVISOR-123', 'type': 'HYPERVISOR'}, {'id': 'HYPERVISOR-345', 'type': 'HYPERVISOR'},{'id': 'HYPERVISOR-456', 'type': 'HYPERVISOR'}]}}

I need to build an array where anything type='HYPERVISOR'. For example, on this data set array needs to be like this:

 hypervisorsName=['HYPERVISOR-123','HYPERVISOR-345','HYPERVISOR-456']

this json file is type dict

I am trying this:

hypervisorsName=resp['fromRelationships']['manages']['id']

I get this error:

TypeError: list indices must be integers or slices, not str

Is there an easy way to do this?

user1471980
  • 10,127
  • 48
  • 136
  • 235
  • 1
    Yes, of course. Use integers to index lists, not strings. In case you aren't aware, `resp['fromRelationships']['manages']` is a list. – mkrieger1 Jul 01 '21 at 20:07
  • This should answer your question: [Getting a list of values from a list of dicts](https://stackoverflow.com/questions/7271482/getting-a-list-of-values-from-a-list-of-dicts) – mkrieger1 Jul 01 '21 at 20:15
  • You can also use pandas json normalizer pd.json_normalize(resp['fromRelationships']['manages']) Then you can list the column you want. list( pd.json_normalize(resp['fromRelationships']['manages'])['id']) Output: ['HYPERVISOR-123', 'HYPERVISOR-345', 'HYPERVISOR-456'] – gurezende Jul 01 '21 at 20:30

1 Answers1

1

resp['fromRelationships']['manages'] is a list. You need to iterate over items in the list and get item['id']. You can use list comprehension like this:

hypervisorsName = [item.get('id')
                   for item in resp['fromRelationships']['manages']
                   if item.get('type') == 'HYPERVISOR']
buran
  • 13,682
  • 10
  • 36
  • 61
  • While code-only answers might answer the question, you could significantly improve the quality of your answer by providing context for your code, a reason for why this code works, and some references to documentation for further reading. – Pranav Hosangadi Jul 01 '21 at 20:10