0

我有 json 格式的文件,'datastores.json',看起来像这样:

{
"{'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

我在上面运行以下代码:

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']

我收到以下错误:

TypeError: string indices must be integers

在这条线上:

esx_host = dstor['ESXi_Host']

我知道它需要一个整数。从我一直在做的阅读来看,如果我加入

'json.loads'

代替

'json.load'

并且还替换了

'(json_file.read())'

代替

'(json_file)'

然后它将文件作为字符串读取并允许字符串解析而不是整数。为什么这不起作用?

4

1 回答 1

0

一个问题是您的 .json 中没有“ESXi_Host”键,它说

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

注意" "它,关键是"{'ESXi_Host': 'elvis.lab.vsphere.com'}"(这是一个字符串)。

其次,加载的对象可能是一个字典,因此形式的迭代

for dstor in datastors:

上(键是字符串,只有整数索引),而不是值,访问值做类似的事情

for _, dstor in datastors.iteritems():

打印datastores并调查解析的 .json 的确切结构是什么。

于 2016-07-07T22:05:44.277 回答