我正在尝试从AWS价格表中提取某些头寸,但是我一直在获取以下错误代码。 JSON结构有错误吗?
Traceback (most recent call last):
File "/Python/python2.py", line 5, in <module>
for r in data['SJQU8C5FNVFYMK7X']:
KeyError: 'SJQU8C5FNVFYMK7X
JSON文件
"SJQU8C5FNVFYMK7X" : {
"sku" : "SJQU8C5FNVFYMK7X",
"productFamily" : "Compute Instance",
"attributes" : {
"servicecode" : "AmazonEC2",
"location" : "Asia Pacific (Singapore)",
"locationType" : "AWS Region",
"instanceType" : "r5n.8xlarge",
"currentGeneration" : "Yes",
"instanceFamily" : "Memory optimized",
"vcpu" : "32",
"physicalProcessor" : "Intel Xeon Platinum 8259 (Cascade Lake)",
"clockSpeed" : "2.5 GHz",
"memory" : "256 GiB",
"storage" : "EBS only",
"networkPerformance" : "25 Gigabit",
"processorArchitecture" : "64-bit",
"tenancy" : "Shared",
"operatingSystem" : "Windows",
"licenseModel" : "No License required",
"usagetype" : "APS1-BoxUsage:r5n.8xlarge",
"operation" : "RunInstances:0102",
"capacitystatus" : "Used",
"dedicatedEbsThroughput" : "5000 Mbps",
"ecu" : "NA",
"enhancedNetworkingSupported" : "No",
"intelAvxAvailable" : "No",
"intelAvx2Available" : "No",
"intelTurboAvailable" : "No",
"normalizationSizeFactor" : "64",
"preInstalledSw" : "SQL Ent",
"servicename" : "Amazon Elastic Compute Cloud"
}
Python代码:
import json
with open('index (5).json') as json_file:
data = json.load(json_file)
for r in data['SJQU8C5FNVFYMK7X']:
print (r)
有什么想法我做错了吗?
答案 0 :(得分:2)
您在整个过程中缺少一些花括号,下面的json可以正确解析
{
"SJQU8C5FNVFYMK7X": {
"sku": "SJQU8C5FNVFYMK7X",
"productFamily": "Compute Instance",
"attributes": {
"servicecode": "AmazonEC2",
"location": "Asia Pacific (Singapore)",
"locationType": "AWS Region",
"instanceType": "r5n.8xlarge",
"currentGeneration": "Yes",
"instanceFamily": "Memory optimized",
"vcpu": "32",
"physicalProcessor": "Intel Xeon Platinum 8259 (Cascade Lake)",
"clockSpeed": "2.5 GHz",
"memory": "256 GiB",
"storage": "EBS only",
"networkPerformance": "25 Gigabit",
"processorArchitecture": "64-bit",
"tenancy": "Shared",
"operatingSystem": "Windows",
"licenseModel": "No License required",
"usagetype": "APS1-BoxUsage:r5n.8xlarge",
"operation": "RunInstances:0102",
"capacitystatus": "Used",
"dedicatedEbsThroughput": "5000 Mbps",
"ecu": "NA",
"enhancedNetworkingSupported": "No",
"intelAvxAvailable": "No",
"intelAvx2Available": "No",
"intelTurboAvailable": "No",
"normalizationSizeFactor": "64",
"preInstalledSw": "SQL Ent",
"servicename": "Amazon Elastic Compute Cloud"
}
}
}
请注意,您可以使用在线短绒棉签来检查解析错误(例如https://jsonlint.com/)
答案 1 :(得分:1)
调试此问题的简单方法是打开一个交互式解释器会话,并查看存在哪些键:
>>> import json
>>> json_file = open('index (5).json')
>>> data = json.load(json_file)
>>> data.keys()
如果您想完全操纵data.keys()
,则可能希望将其作为列表(即list(data.keys())
)。但这至少会告诉您json.load
认为键是什么。