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

如何将TypeScript编译器错误保存为JSON文件?

把错误输出转成JSON格式的方法

首先得明确:--pretty参数大多是用来让已有的JSON输出更美观(换行、缩进),但它本身不会把普通文本错误转换成JSON。你得先让工具输出JSON格式,再考虑保存或者美化。

1. 优先用工具自带的JSON输出功能

大部分代码检查、编译工具都有专门的JSON输出选项,常用的参数是--format json或者-f json,举几个常见例子:

  • RuboCop(Ruby代码检查):rubocop --format json > errors.json
  • ESLint(JS/TS代码检查):eslint --format json src/ > errors.json
  • flake8(Python代码检查):flake8 --format=json src/ > errors.json
    如果工具支持--pretty,可以和JSON格式一起用,输出带缩进的美观JSON:some_tool --format json --pretty > errors.json

2. 工具没JSON输出?自己写脚本转

如果你的工具只能输出普通文本错误,比如每行一条的格式(文件:行号: 错误信息),可以用Ruby或Python写个小脚本转成JSON:

Ruby 脚本示例

errors = []
# 读取标准输入的错误内容
ARGF.each_line do |line|
  next if line.strip.empty?
  # 拆分错误行的三部分:文件、行号、错误信息
  file, line_num, message = line.split(': ', 3)
  errors << {
    file: file&.strip,
    line: line_num&.to_i,
    message: message&.strip
  }
end

require 'json'
# 写入带缩进的JSON文件
File.write('errors.json', JSON.pretty_generate(errors))

使用方式:把工具的错误输出导到这个脚本,比如your_tool | ruby error_to_json.rb,或者先保存错误到文本再处理:ruby error_to_json.rb < error_log.txt

Python 脚本示例

import json

errors = []
# 读取错误日志文件
with open('error_log.txt', 'r', encoding='utf-8') as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        parts = line.split(': ', 2)
        if len(parts) >= 3:
            file, line_num, message = parts
            errors.append({
                'file': file.strip(),
                'line': int(line_num) if line_num.isdigit() else None,
                'message': message.strip()
            })

# 写入格式化后的JSON
with open('errors.json', 'w', encoding='utf-8') as f:
    json.dump(errors, f, indent=2, ensure_ascii=False)

使用方式:先把工具错误保存到error_log.txt,然后运行python error_to_json.py

3. 别再踩--pretty的坑

记住:--pretty的作用是美化已经是JSON格式的输出,不是把文本转成JSON。如果工具本身不输出JSON,加--pretty只会让普通错误文本排版整齐一点,不会变成你要的JSON格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:45:49