JSON/Python解码

2024-05-13 00:11:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个json格式的文件数据存储.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)'

然后它将文件作为字符串读入,并允许字符串解析而不是整数。为什么不起作用?你知道吗


Tags: 文件字符串jsonhostread整数filedatastore
1条回答
网友
1楼 · 发布于 2024-05-13 00:11:42

它说,一个问题是您的.json中没有“ESXi\u Host”键

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

注意""在它周围,键是"{'ESXi_Host': 'elvis.lab.vsphere.com'}"(这是一个字符串)。你知道吗

第二,加载的对象可能是一个字典,因此需要对表单进行迭代

for dstor in datastors:

通过键(键是字符串,只有整数索引),而不是值来访问值

for _, dstor in datastors.iteritems():

打印datastores并研究解析的.json的确切结构。你知道吗

相关问题 更多 >