本文目录导读:

我来介绍几种批量格式化JSON文件的脚本方法:
使用 Node.js 脚本
// format-json.js
const fs = require('fs');
const path = require('path');
// 需要处理的文件夹路径
const jsonDir = './json-files';
// 递归查找所有JSON文件
function findJsonFiles(dir, files = []) {
const items = fs.readdirSync(dir, { withFileTypes: true });
for (const item of items) {
const fullPath = path.join(dir, item.name);
if (item.isDirectory()) {
findJsonFiles(fullPath, files);
} else if (path.extname(item.name) === '.json') {
files.push(fullPath);
}
}
return files;
}
// 格式化JSON文件
function formatJsonFile(filePath) {
try {
const content = fs.readFileSync(filePath, 'utf8');
const jsonData = JSON.parse(content);
const formatted = JSON.stringify(jsonData, null, 2);
fs.writeFileSync(filePath, formatted, 'utf8');
console.log(`✅ 已格式化: ${filePath}`);
} catch (error) {
console.error(`❌ 格式化失败: ${filePath}`, error.message);
}
}
// 主函数
function main() {
if (!fs.existsSync(jsonDir)) {
console.error(`文件夹不存在: ${jsonDir}`);
return;
}
const jsonFiles = findJsonFiles(jsonDir);
console.log(`找到 ${jsonFiles.length} 个JSON文件`);
jsonFiles.forEach(formatJsonFile);
console.log('全部格式化完成!');
}
main();
使用 Python 脚本
# format_json.py
import json
import os
from pathlib import Path
def find_json_files(directory):
"""递归查找所有JSON文件"""
json_files = []
for path in Path(directory).rglob('*.json'):
json_files.append(str(path))
return json_files
def format_json_file(file_path):
"""格式化单个JSON文件"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"✅ 已格式化: {file_path}")
return True
except Exception as e:
print(f"❌ 格式化失败: {file_path} - {str(e)}")
return False
def main():
# 指定包含JSON文件的文件夹
json_dir = "./json-files"
if not os.path.exists(json_dir):
print(f"文件夹不存在: {json_dir}")
return
json_files = find_json_files(json_dir)
print(f"找到 {len(json_files)} 个JSON文件")
formatted_count = 0
for file_path in json_files:
if format_json_file(file_path):
formatted_count += 1
print(f"成功格式化 {formatted_count}/{len(json_files)} 个文件")
if __name__ == "__main__":
main()
使用 jq 命令行工具
#!/bin/bash
# format-json.sh
# 递归查找并格式化所有JSON文件
find ./json-files -name "*.json" -type f | while read file; do
if jq '.' "$file" > /tmp/temp.json 2>/dev/null; then
mv /tmp/temp.json "$file"
echo "✅ 已格式化: $file"
else
echo "❌ 格式化失败: $file"
fi
done
PowerShell 脚本 (Windows)
# format-json.ps1
$jsonDir = ".\json-files"
# 获取所有JSON文件
$jsonFiles = Get-ChildItem -Path $jsonDir -Recurse -Filter "*.json"
Write-Host "找到 $($jsonFiles.Count) 个JSON文件"
foreach ($file in $jsonFiles) {
try {
# 读取JSON内容
$content = Get-Content -Path $file.FullName -Raw
$jsonObj = $content | ConvertFrom-Json
# 格式化为漂亮格式
$formatted = $jsonObj | ConvertTo-Json -Depth 100
# 写入文件
$formatted | Out-File -FilePath $file.FullName -Encoding UTF8
Write-Host "✅ 已格式化: $($file.FullName)" -ForegroundColor Green
}
catch {
Write-Host "❌ 格式化失败: $($file.FullName) - $($_.Exception.Message)" -ForegroundColor Red
}
}
Write-Host "全部格式化完成!" -ForegroundColor Cyan
使用特定的格式化配置
如果你需要特定的格式化方式,可以创建配置文件:
// formatter-config.js
const config = {
indent: 4, // 缩进空格数
sortKeys: false, // 是否排序键
preserveComments: false, // 是否保留注释(需要特殊处理)
encoding: 'utf8' // 文件编码
};
function formatWithConfig(jsonStr, config) {
const obj = JSON.parse(jsonStr);
if (config.sortKeys) {
return JSON.stringify(obj, Object.keys(obj).sort(), config.indent);
}
return JSON.stringify(obj, null, config.indent);
}
使用说明
- 创建文件夹:将所有JSON文件放入
json-files文件夹 - 运行脚本:
- Node.js:
node format-json.js - Python:
python format_json.py - Bash:
chmod +x format-json.sh && ./format-json.sh - PowerShell:
.\format-json.ps1
- Node.js:
注意事项
- 备份文件:运行前建议备份原始文件
- 编码问题:确保JSON文件使用UTF-8编码
- 大文件:处理大文件时注意内存使用
- 错误处理:脚本会跳过无效的JSON文件
选择哪种方法取决于你的环境和技术栈偏好,Node.js和Python脚本最灵活,而jq和PowerShell适合快速部署。