tnunu tnunu - 4 months ago 24
JSON Question

JSON/Python - decoding

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?

Answer

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.

Comments