tnunu tnunu - 1 year ago 94
JSON Question

JSON/Python - decoding

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

"{'ESXi_Host': ''}": {
"": {
"capacity": 293131517952,
"uuid": "57431578-630f1322-7bf2-00212883a5b0",
"vmfs_version": "5.60",
"ssd": false,
"extents": [
"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(
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


instead of


and also subbed in


instead of


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

Answer Source

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

"{'ESXi_Host': ''}"

notice " " around it, the key is "{'ESXi_Host': ''}" (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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download