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

如何用Python移除JSON文件中数组末尾元素后的逗号

解决Python生成JSON数组末尾多余逗号的问题

最优方案:用内置json模块自动生成

别手动拼接JSON字符串,Python自带的json模块会帮你完美处理格式,完全避免多余逗号的问题,而且天然适配多月份的场景。

示例代码:

import json

# 构造多月份的数据结构,直接用Python的字典和列表
monthly_data = {
    "January": [12, 27, 31],
    "February": [5, 14, 22],
    "March": [3, 17, 29]
}

# 生成格式化的JSON字符串,indent参数用来美化排版
json_content = json.dumps(monthly_data, indent=4)

# 写入文件
with open("monthly_days.json", "w", encoding="utf-8") as file:
    file.write(json_content)

运行后生成的JSON里,所有数组的最后一个元素都不会带多余逗号,不管你加多少个月份的数据都能适配。

手动拼接的替代方案(不推荐)

如果因为特殊需求必须手动拼接字符串,别逐个元素加逗号,先把所有元素存成字符串列表,再用", "连接后套上数组括号:

# 处理单个月份的天数列表
days_list = ["12", "27", "31"]
# 用join方法拼接,自动处理逗号
array_str = f"[{', '.join(days_list)}]"

# 多月份的情况可以循环处理
monthly_data_str = "{"
months = {
    "January": ["12", "27", "31"],
    "February": ["5", "14", "22"]
}
for month, days in months.items():
    days_str = f"[{', '.join(days)}]"
    monthly_data_str += f'"{month}": {days_str}, '
# 最后去掉末尾的逗号和空格,再加闭合括号
monthly_data_str = monthly_data_str.rstrip(", ") + "}"

# 写入文件
with open("monthly_days_manual.json", "w", encoding="utf-8") as file:
    file.write(monthly_data_str)

这种方法也能避免多余逗号,但不如用json模块省心,容易出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 12:34:53