0

I've got json formatted file, 'datastores.json' that looks like this:

{
"{'ESXi_Host': 'elvis.lab.vsphere.com'}": {
    "elvis.data": {
        "capacity": 293131517952, 
            "uuid": "57431578-630f1322-7bf2-00212883a5b0", 
            "vmfs_version": "5.60", 
            "ssd": false, 
            "extents": [
                "mpx.vmhba1:C0:T1:L0"
            ], 
            "local": true

I am running the following code on it:

import json

with open("C:\PyVmomi_out\\datastores.json") as json_file:
datastores = json.loads(json_file.read())
for dstor in datastores:
    esx_host = dstor['ESXi_Host']
    datastore = dstor['datastore']

I get the following error:

TypeError: string indices must be integers

On this line:

esx_host = dstor['ESXi_Host']

I understand that it is expecting an integer. From the reading I had been doing I though if I subbed in

'json.loads'

instead of

'json.load'

and also subbed in

'(json_file.read())'

instead of

'(json_file)'

then it would read the file in as string and allow string parsing instead of integers. Why didn't this work?

William Jackson
  • 1,130
  • 10
  • 24
tnunu
  • 15
  • 5

1 Answers1

0

One problem is you do not have "ESXi_Host" key in your .json, it says

"{'ESXi_Host': 'elvis.lab.vsphere.com'}"

notice " " around it, the key is "{'ESXi_Host': 'elvis.lab.vsphere.com'}" (this is a single string).

Second, loaded object will be probably a dictionary, thus iteration of form

for dstor in datastors:

is over keys (and keys are strings, which have only integer indexes), not values, to access values do something like

for _, dstor in datastors.iteritems():

Print your datastores and investigate what is the exact structure of your parsed .json.

lejlot
  • 64,777
  • 8
  • 131
  • 164
  • I did not realize the single string would be a problem. The error msg mentions "integers", confusing. I am struggling to figure out how to fix the formatting so that the two strings are indeed split . The script for pulling the ESXi hosts/datastores in json format makes the host/datastore name the primary key. For dynamoDB I need them to have label of "ESXi_Host" and "datastore" as primary key and the corresponding names as the key-values. This is proving to be more difficult than I thought. I'll go back to the script that pulls the data from vsphere and keep trying to modify it. Thanks again! – tnunu Jul 07 '16 at 22:16
  • Error regarding integers comes from the wrong iteration. You iterate over keys, keys are strings, and string have only integer indexes. – lejlot Jul 07 '16 at 22:18