JSON/Python - 解码

JSON/Python - decoding

我有 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)'

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

一个问题是你的 .json 中没有 "ESXi_Host" 键,它说

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

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

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

for dstor in datastors:

超过了 keys(键是字符串,只有 整数索引 ),而不是值,要访问值,请执行类似

for _, dstor in datastors.iteritems():

打印您的 datastores 并调查您解析的 .json.

的确切结构是什么