Python如何从JSON数据中提取detectedName、cpuCores字段并导出为CSV
错误原因
你要提取的detectedName、cpuCores两个字段并非JSON根节点下的直接字段,而是嵌套在根节点的properties对象中,直接从data中访问detectedName自然会触发键不存在的报错。同时你写的data['detectedName']['cpuCores']也不符合字段结构,两个字段是同级关系,不存在嵌套关联。
解决步骤
1. 先修正JSON格式
你给出的示例JSON存在语法错误,根节点末尾多余的]需要删除,否则JSON解析阶段就会报错,修正后结构如下:
{ "properties": { "detectedName": "servername1", "cpuCores": 60 } }
2. 正确提取字段
将JSON解析为Python字典后,需要先访问properties节点,再提取对应子字段:
import json # 假设json_str为你的原始JSON字符串 data = json.loads(json_str) properties = data["properties"] # 提取目标字段 detected_name = properties["detectedName"] cpu_cores = properties["cpuCores"]
如果要避免字段缺失引发的报错,可以用get方法设置默认值:
detected_name = properties.get("detectedName", "未识别名称") cpu_cores = properties.get("cpuCores", 0)
3. 导出CSV示例
完成字段提取后可以直接用Python内置的csv模块导出:
import csv # 假设你有多个JSON解析后的数据存在data_list中 output_rows = [] for item in data_list: prop = item["properties"] output_rows.append({ "detectedName": prop.get("detectedName", "未识别名称"), "cpuCores": prop.get("cpuCores", 0) }) # 写入CSV文件 with open("server_info.csv", "w", newline="", encoding="utf-8-sig") as f: writer = csv.DictWriter(f, fieldnames=["detectedName", "cpuCores"]) writer.writeheader() writer.writerows(output_rows)
内容的提问来源于stack exchange,提问作者user1471980
相关产品推荐
相关产品推荐

