如何将git log输出按字段映射转换为JSON格式文件
Git 制表符分隔日志转JSON 实现方法
你的git log命令输出使用\t(制表符)作为固定分隔符,四个字段顺序为提交哈希、提交作者、提交日期、提交信息,以下两种方案都可以稳定生成标准格式的JSON文件,能自动处理提交信息包含特殊字符、制表符的边界场景,不会出现格式错误。
方案1:Git + jq 一键生成(推荐)
jq是专用的JSON命令行处理工具,转义逻辑严谨,执行效率高,单条命令即可完成转换,结果直接写入commits.json文件:
git log --all --pretty=format:"%h%x09%an%x09%ad%x09%s" --date=short --no-merges | jq -R -s ' split("\n") | map(select(length > 0)) | map(split("\t")) | map({ sha: .[0], author: .[1], date: .[2], commit_message: .[3:] | join("\t") }) ' > commits.json
针对你给出的示例输入,转换后的JSON内容为:
[ { "sha": "84hf6f3", "author": "Some Author", "date": "2022-07-13", "commit_message": "some commit message" } ]
方案2:Python 内置模块实现(无额外依赖)
如果不想额外安装jq,绝大多数系统都预装了Python3,可以直接用内置的json模块处理,不需要安装第三方依赖:
git log --all --pretty=format:"%h%x09%an%x09%ad%x09%s" --date=short --no-merges | python3 -c ' import sys import json commits = [] for line in sys.stdin: line = line.rstrip("\n") if not line: continue # 最多分割3次,避免提交信息内含制表符导致字段错位 parts = line.split("\t", 3) if len(parts) < 4: continue sha, author, date, commit_msg = parts commits.append({ "sha": sha, "author": author, "date": date, "commit_message": commit_msg }) with open("commits.json", "w", encoding="utf-8") as f: json.dump(commits, f, ensure_ascii=False, indent=2) '
注意:不推荐直接用awk、shell字符串拼接的方式生成JSON,一旦提交信息包含双引号、反斜杠、换行符等特殊字符,生成的文件会出现JSON格式错误,无法正常解析。以上两种方案都内置了标准转义逻辑,不会出现这类问题。
内容的提问来源于stack exchange,提问作者BeginnerDev
相关产品推荐
相关产品推荐

