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

Python中如何将指定列名列表转换为特定结构的ColumnNames JSON格式

实现列名列表到目标JSON结构的转换

很简单,咱们分两步就能轻松搞定这个转换,用Python的列表推导式和json模块就足够了:

步骤1:生成内部的字典数组

首先把你的列名列表转换成一个个包含field键的字典,用列表推导式是最简洁的写法:

column = ['orderID', 'productID', 'unitPrice', 'quantity', 'discount']
# 生成每个元素为{"field": 列名}的列表
column_items = [{"field": col} for col in column]

步骤2:包裹成目标结构并转为JSON字符串

接下来把上面的列表放到以ColumnNames为键的字典里,再用json.dumps()把字典序列化为标准JSON格式(加indent参数能让输出的JSON更易读):

import json

# 构建最终的字典结构
result_dict = {"ColumnNames": column_items}
# 序列化为带缩进的JSON字符串
result_json = json.dumps(result_dict, indent=2)

print(result_json)

运行这段代码后,你会得到完全符合需求的输出:

{
  "ColumnNames": [
    {
      "field": "orderID"
    },
    {
      "field": "productID"
    },
    {
      "field": "unitPrice"
    },
    {
      "field": "quantity"
    },
    {
      "field": "discount"
    }
  ]
}

要是你需要把列名替换成示例里的Status、order这类自定义名称,只需要修改原始column列表里的内容就行,代码逻辑完全不用调整~

内容的提问来源于stack exchange,提问作者alla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:38:11