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

如何移除JSON文件中的/*类型注释?commentjson处理该类注释会崩溃

解决方法

你可以先通过正则预处理文件内容,提前移除所有/* */包裹的块注释,再传给commentjson处理即可,修改后的代码如下:

import re
import commentjson

# 读取原始文件内容
with open(f"{i['Location']}\\{file_name}", 'r', encoding='utf-8') as f:
    raw_content = f.read()

# 移除所有块注释:非贪婪匹配/*到*/之间的所有内容(包括换行)
content_without_block_comment = re.sub(r'/\*[\s\S]*?\*/', '', raw_content)

# 加载处理后的内容,commentjson会自动处理剩余的//单行注释
json_info = commentjson.loads(content_without_block_comment)
json_info['password'] = password

# 写入更新后的文件
with open(f"{i['location_Daily']}\\{file_name}", 'w', encoding='utf-8') as f:
    commentjson.dump(json_info, f, indent=4)
print("updated")

注意事项

  • 新增的encoding='utf-8'参数可以避免不同系统环境下的编码解析异常,建议保留
  • 上述正则可以覆盖绝大多数无嵌套的块注释场景,JSON规范本身也不支持注释嵌套,完全适配你的需求
  • 批量运行前可以先打印content_without_block_comment验证是否有误删正常内容的情况,确认没问题再全量执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:36:03