[英]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'}"
(这是一个字符串)。
其次,加载的对象可能是一个dictionary ,因此是形式的迭代
for dstor in datastors:
在键上 (键是字符串,只具有整数索引 ),而不是值,访问值的操作类似于
for _, dstor in datastors.iteritems():
打印您的datastores
并调查解析后的.json的确切结构是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.