You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 19:39:01