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

如何为DataFrame的每一行生成指定结构的JSON数组?

解决方案

方法1:为每行生成独立的JSON数组

直接通过apply遍历DataFrame的每一行,将行数据映射为指定的JSON结构:

代码实现

import pandas as pd
import json

# 构造目标DataFrame
data = {
    'techniqueID': ['T1078', 'T1078', 'T1078', 'T1078', 'T1110', 'T1070', 'T1059', 'T1114', 'T1098'],
    'Value': [13, 13, 13, 13, 5, 3, 3, 3, 3],
    'color': ['#74c476', '#74c476', '#74c476', '#74c476', '#74c476', '#a1d99b', '#a1d99b', '#a1d99b', '#a1d99b'],
    'tactic': ['Defense-Evasion', 'Initial-Access', 'Persistence', 'Privilege-Escalation', 'Credential-Access', 'Defense-Evasion', 'Execution', 'Collection', 'Persistenc']
}
df = pd.DataFrame(data)

# 定义行转JSON的函数
def row_to_tech_json(row):
    tech_item = {
        "techniqueID": row['techniqueID'],
        "tactic": row['tactic'],
        "color": row['color'],
        "comment": "",
        "enabled": True,
        "metadata": [],
        "links": [],
        "showSubtechniques": False
    }
    return json.dumps({"techniques": [tech_item]}, indent=4)

# 为每行生成JSON并保存为新列
df['techniques_json'] = df.apply(row_to_tech_json, axis=1)

# 查看第一行结果
print(df['techniques_json'].iloc[0])

输出示例(第一行)

{
    "techniques": [
        {
            "techniqueID": "T1078",
            "tactic": "Defense-Evasion",
            "color": "#74c476",
            "comment": "",
            "enabled": true,
            "metadata": [],
            "links": [],
            "showSubtechniques": false
        }
    ]
}

方法2:生成包含所有行的完整JSON数组

如果需要将所有行数据合并为一个统一的techniques数组,可直接遍历构造列表后转为JSON:

代码实现

techniques_list = []
for _, row in df.iterrows():
    techniques_list.append({
        "techniqueID": row['techniqueID'],
        "tactic": row['tactic'],
        "color": row['color'],
        "comment": "",
        "enabled": True,
        "metadata": [],
        "links": [],
        "showSubtechniques": False
    })

# 生成完整JSON
full_tech_json = json.dumps({"techniques": techniques_list}, indent=4)
print(full_tech_json)

关键说明

  • 无需先将JSON转成DataFrame再合并,直接从原DataRow提取字段填充目标结构是最高效的方式。
  • 如果需要保留Value字段,可将其加入metadata数组,例如修改metadata为[{"key": "Value", "value": row['Value']}]。

内容的提问来源于stack exchange,提问作者S3c-R3search

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:20:40