Python提取JSON中InstanceType并统计数量问题求助
问题:提取并统计JSON中InstanceType的出现次数
我想用Python从JSON文件里导出InstanceType字段,统计每种实例类型的数量,只需要获取该字段及其出现次数。以下是JSON文件片段:
"InstanceTypes": [ { "InstanceType": "c7gn.xlarge", "CurrentGeneration": true, "FreeTierEligible": false, "SupportedUsageClasses": [ "on-demand", "spot" ], "SupportedRootDeviceTypes": [ "ebs" ], "SupportedVirtualizationTypes": [ "hvm" ], "BareMetal": false, "Hypervisor": "nitro", "ProcessorInfo": { "SupportedArchitectures": [ "arm64" ], "SustainedClockSpeedInGhz": 2.6 }, "VCpuInfo": { "DefaultVCpus": 4, "DefaultCores": 4, "DefaultThreadsPerCore": 1, "ValidCores": [ 1, 2, 3, 4 ], "ValidThreadsPerCore": [ 1 ] }, "MemoryInfo": { "SizeInMiB": 8192 }, "InstanceStorageSupported": false, "EbsInfo": { "EbsOptimizedSupport": "default", "EncryptionSupport": "supported", "EbsOptimizedInfo": { "BaselineBandwidthInMbps": 2083, "BaselineThroughputInMBps": 260.375, "BaselineIops": 8333, "MaximumBandwidthInMbps": 10000, "MaximumThroughputInMBps": 1250.0, "MaximumIops": 40000 }, "NvmeSupport": "required" }, "NetworkInfo": { "NetworkPerformance": "Up to 40 Gigabit", "MaximumNetworkInterfaces": 4, "MaximumNetworkCards": 1, "DefaultNetworkCardIndex": 0, "NetworkCards": [ { "NetworkCardIndex": 0, "NetworkPerformance": "Up to 40 Gigabit", "MaximumNetworkInterfaces": 4, "BaselineBandwidthInGbps": 12.5, "PeakBandwidthInGbps": 40.0 } ], "Ipv4AddressesPerInterface": 15, "Ipv6AddressesPerInterface": 15, "Ipv6Supported": true, "EnaSupport": "required", "EfaSupported": false, "EncryptionInTransitSupported": true, "EnaSrdSupported": false }, "PlacementGroupInfo": { "SupportedStrategies": [ "cluster", "partition", "spread" ] }, "HibernationSupported": false, "BurstablePerformanceSupported": false, "DedicatedHostsSupported": true, "AutoRecoverySupported": true, "SupportedBootModes": [ "uefi" ], "NitroEnclavesSupport": "unsupported", "NitroTpmSupport": "unsupported" } ]
我编写了如下Python代码,但执行时提示找不到InstanceType字段,明明JSON结构包含该字段,却无法解决:
import json def extract_string_from_json(json_file_path, key): with open(json_file_path, 'r') as file: data = json.load(file) # Navigate through the JSON structure to access the specific string # For example, if the string is nested within dictionaries and lists: string_value = data.get(key, "Key not found") return string_value # Example usage: json_file_path = r'C:\Users\Path\Documents\ptah\Python\path\data.json' # Replace 'data.json' with your JSON file path key_to_extract = 'InstanceType' # Replace 'specific_key' with the key containing the string string_value = extract_string_from_json(json_file_path, key_to_extract) if string_value != "Key not found": print("String value:", string_value) else: print(f"Key '{key_to_extract}' not found in JSON file.")
问题根源
你的代码直接在JSON顶层对象中查找InstanceType,但实际上这个字段是嵌套在InstanceTypes数组下的每个子对象里的,顶层JSON对象并没有InstanceType这个key,所以会提示找不到。
修正后的代码
要遍历InstanceTypes数组,提取每个元素的InstanceType值,再用collections.Counter来统计每种类型的出现次数:
import json from collections import Counter def count_instance_types(json_file_path): with open(json_file_path, 'r') as file: data = json.load(file) # 获取InstanceTypes数组,若不存在则返回空列表 instance_types = data.get("InstanceTypes", []) # 提取每个实例的InstanceType字段,过滤缺失该字段的对象 type_list = [item.get("InstanceType") for item in instance_types if item.get("InstanceType")] # 统计次数 type_counts = Counter(type_list) return type_counts # 使用示例 json_file_path = r'C:\Users\Path\Documents\ptah\Python\path\data.json' counts = count_instance_types(json_file_path) # 打印结果 for instance_type, count in counts.items(): print(f"{instance_type}: {count}")
说明
- 先从JSON中取出
InstanceTypes数组,避免因数组不存在导致报错; - 遍历数组中的每个对象,提取
InstanceType值,过滤掉可能缺失该字段的对象; - 用
Counter快速统计每种类型的出现次数,最后遍历输出结果。
内容的提问来源于stack exchange,提问作者rodriguezrj
相关产品推荐
相关产品推荐

