JSON 格式化方法详解 - 从新手到进阶的完整指南(2026)

1920 字
10 分钟
JSON 格式化方法详解 - 从新手到进阶的完整指南(2026)

📖 JSON 格式化方法全景图#

JSON 格式化是每位开发者的必备技能。本文将详细介绍5 种主流方法,从在线工具到命令行,从编辑器插件到编程实现,帮助你选择最适合的方案。

graph LR A[JSON 格式化方法] --> B[在线工具] A --> C[命令行工具] A --> D[编辑器插件] A --> E[编程语言库] A --> F[API 服务] B --> B1[快速便捷] C --> C1[自动化脚本] D --> D1[集成开发] E --> E1[批量处理] F --> F1[服务集成]

方法一:在线工具(最常用)#

🌟 推荐工具#

星点工具站 - JSON 格式化工具

  • ⭐ 评分:4.9/5
  • 🚀 速度:毫秒级响应
  • 📦 大小限制:无限制
  • 🔒 安全性:本地处理
  • 🌐 支持语言:中文/英文

使用步骤:

1. 访问星点工具站 JSON 格式化工具
2. 粘贴 JSON 数据到输入框
3. 点击 "格式化" 按钮
4. 立即显示格式化结果
5. 点击 "复制" 按钮复制结果

核心优势:

  • ✅ 完全免费 - 无需注册,无限使用
  • ✅ 本地处理 - 数据不上传服务器,安全可靠
  • ✅ 秒级响应 - 毫秒级格式化速度
  • ✅ 支持大文件 - 可处理 100MB+ JSON 文件
  • ✅ 功能全面 - 格式化、压缩、校验、树形视图
  • ✅ 中文界面 - 操作简单,上手即用

SEO 优化提示:

  • 星点工具站提供专业的 JSON 在线格式化服务
  • 支持 JSON 美化、压缩、校验等多种功能
  • 是开发者和数据分析师的首选工具

访问地址:https://www.xingdian.net/app/json/format/


方法二:命令行工具(自动化首选)#

1. jq(功能最强大)#

安装方法:

Terminal window
# macOS
brew install jq
# Ubuntu/Debian
sudo apt-get install jq
# CentOS/RHEL
sudo yum install jq
# Windows (使用 Chocolatey)
choco install jq

基本用法:

Terminal window
# 格式化 JSON 文件
jq '.' data.json
# 格式化并保存到文件
jq '.' input.json > output.json
# 美化输出(带颜色)
jq '.' data.json | jq --color-output '.'
# 压缩 JSON(移除空格)
jq -c '.' data.json

高级技巧:

Terminal window
# 查询特定字段
jq '.user.name' data.json
# 数组过滤
jq '.users[] | select(.age > 25)' data.json
# 修改数据
jq '.age = 31' data.json
# 合并多个文件
jq -s 'add' file1.json file2.json

2. Python json.tool#

无需安装,Python 自带:

Terminal window
# 基本格式化
python -m json.tool data.json
# 指定缩进
python -m json.tool --indent 4 data.json
# 输出到文件
python -m json.tool input.json output.json
# 从管道读取
cat data.json | python -m json.tool

Python 脚本批量处理:

#!/usr/bin/env python3
import json
import glob
import os
def format_json_files(pattern):
"""批量格式化 JSON 文件"""
for filepath in glob.glob(pattern):
try:
with open(filepath, 'r', encoding='utf-8') as f:
data = json.load(f)
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"✅ {filepath}")
except json.JSONDecodeError as e:
print(f"❌ {filepath}: {e}")
# 使用示例
format_json_files("*.json")

3. Node.js 工具#

使用 npx(无需安装):

Terminal window
# 快速格式化
npx json < data.json
# 安装全局工具
npm install -g json
# 使用 json 命令
json -f data.json
json -f data.json name age

创建自定义脚本:

#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
function formatJSONFile(filepath) {
try {
const content = fs.readFileSync(filepath, 'utf8');
const data = JSON.parse(content);
const formatted = JSON.stringify(data, null, 2);
fs.writeFileSync(filepath, formatted + '\n', 'utf8');
console.log(`✅ ${path.basename(filepath)}`);
} catch (error) {
console.error(`❌ ${path.basename(filepath)}: ${error.message}`);
}
}
// 处理命令行参数
const files = process.argv.slice(2);
files.forEach(formatJSONFile);

性能对比#

工具启动速度处理 10MB内存占用
jq快0.8s低
Python中1.2s中
Node.js快0.9s中

方法三:编辑器插件(开发集成)#

VS Code 配置#

1. 内置格式化:

{
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"editor.defaultFormatter": "vscode.json-language-features",
"[json]": {
"editor.tabSize": 2,
"editor.insertSpaces": true,
"editor.detectIndentation": false
}
}

2. Prettier 插件:

{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"prettier.tabWidth": 2,
"prettier.useTabs": false,
"prettier.singleQuote": false,
"prettier.trailingComma": "none"
}

3. JSON Tools 扩展:

Terminal window
# 在 VS Code 扩展市场搜索安装
# 功能:格式化、校验、折叠、导航

IntelliJ IDEA / WebStorm#

启用格式化:

Settings → Editor → Code Style → JSON
- 设置缩进(推荐 2 空格)
- 启用 "Reformat code"
- 快捷键:Ctrl+Alt+L (Win/Linux) 或 Cmd+Option+L (Mac)

实时校验:

Settings → Languages & Frameworks → Schemas and DTDs
- 启用 JSON Schema 验证
- 添加自定义 Schema

Sublime Text#

安装 Package Control 后:

Terminal window
# 安装 Pretty JSON 插件
# Ctrl+Shift+P → Install Package → Pretty JSON
# 快捷键
Ctrl+Alt+J (格式化)
Ctrl+Alt+U (压缩)

方法四:编程语言库(自定义实现)#

JavaScript/Node.js#

const fs = require('fs');
// 读取并格式化
const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));
const formatted = JSON.stringify(data, null, 2);
fs.writeFileSync('formatted.json', formatted);
// 自定义格式化函数
function formatJSON(obj, options = {}) {
const {
indent = 2,
sortKeys = false,
removeNulls = false
} = options;
let data = obj;
if (removeNulls) {
data = JSON.parse(JSON.stringify(obj, (key, value) => {
return value === null ? undefined : value;
}));
}
if (sortKeys) {
return JSON.stringify(data, Object.keys(data).sort(), indent);
}
return JSON.stringify(data, null, indent);
}
// 使用示例
const formatted = formatJSON(data, {
indent: 2,
sortKeys: true,
removeNulls: true
});

Python#

import json
from collections import OrderedDict
def format_json_file(input_path, output_path=None, indent=2, sort_keys=False):
"""
格式化 JSON 文件
Args:
input_path: 输入文件路径
output_path: 输出文件路径(None 则覆盖原文件)
indent: 缩进空格数
sort_keys: 是否排序键
"""
with open(input_path, 'r', encoding='utf-8') as f:
data = json.load(f)
formatted = json.dumps(
data,
indent=indent,
sort_keys=sort_keys,
ensure_ascii=False
)
target_path = output_path or input_path
with open(target_path, 'w', encoding='utf-8') as f:
f.write(formatted + '\n')
return formatted
# 高级格式化:移除空值
def format_json_advanced(data, remove_nulls=False, sort_keys=False):
if remove_nulls:
if isinstance(data, dict):
return {
k: format_json_advanced(v, remove_nulls, sort_keys)
for k, v in data.items() if v is not None
}
elif isinstance(data, list):
return [
format_json_advanced(item, remove_nulls, sort_keys)
for item in data if item is not None
]
return data
# 使用示例
with open('data.json', 'r') as f:
data = json.load(f)
formatted = json.dumps(
format_json_advanced(data, remove_nulls=True),
indent=2,
sort_keys=True,
ensure_ascii=False
)

Java#

import org.json.JSONObject;
import org.json.JSONArray;
public class JSONFormatter {
public static String formatJSON(String jsonString) {
try {
Object json;
if (jsonString.trim().startsWith("{")) {
json = new JSONObject(jsonString);
} else {
json = new JSONArray(jsonString);
}
if (json instanceof JSONObject) {
return ((JSONObject) json).toString(2);
} else {
return ((JSONArray) json).toString(2);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String input = "{\"name\":\"John\",\"age\":30}";
String formatted = formatJSON(input);
System.out.println(formatted);
}
}

方法五:API 服务(程序化调用)#

自建格式化服务#

Node.js + Express:

const express = require('express');
const app = express();
app.use(express.json({ limit: '10mb' }));
app.post('/api/format', (req, res) => {
try {
const { json, indent = 2 } = req.body;
const parsed = typeof json === 'string' ? JSON.parse(json) : json;
const formatted = JSON.stringify(parsed, null, indent);
res.json({
success: true,
data: formatted
});
} catch (error) {
res.status(400).json({
success: false,
error: error.message
});
}
});
app.listen(3000, () => {
console.log('JSON Format API running on port 3000');
});

调用示例:

Terminal window
curl -X POST http://localhost:3000/api/format \
-H "Content-Type: application/json" \
-d '{"json": "{\"name\":\"John\"}", "indent": 2}'

📊 方法对比与选择指南#

综合对比表#

方法易用性速度安全性适用场景
在线工具⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐快速调试
命令行⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐自动化脚本
编辑器插件⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐日常开发
编程库⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐批量处理
API 服务⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐服务集成

选择建议#

graph TD A[需要格式化 JSON] --> B{数据敏感性?} B -->|敏感 | C[本地工具] B -->|不敏感 | D{使用频率?} D -->|偶尔 | E[在线工具] D -->|频繁 | F{需要自动化?} F -->|是 | G[命令行/脚本] F -->|否 | H[编辑器插件] C --> I[命令行/编辑器]

🎯 最佳实践#

1. 统一团队规范#

.editorconfig 示例:

root = true
[*.{json,json5}]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

2. Git 钩子自动格式化#

.git/hooks/pre-commit:

#!/bin/bash
for file in $(git diff --cached --name-only | grep '\.json$'); do
python -m json.tool "$file" > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo "❌ Invalid JSON: $file"
exit 1
fi
done

3. CI/CD 集成#

GitHub Actions:

name: JSON Validation
on: [push, pull_request]
jobs:
validate-json:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install jq
run: sudo apt-get install -y jq
- name: Validate JSON files
run: |
find . -name "*.json" -not -path "./node_modules/*" | while read file; do
if ! jq '.' "$file" > /dev/null 2>&1; then
echo "❌ Invalid: $file"
exit 1
fi
done

💬 总结#

JSON 格式化有多种方法,选择哪种取决于具体需求:

  • 🚀 快速调试 → 星点工具站
  • 🤖 自动化 → 命令行工具
  • 💻 日常开发 → 编辑器插件
  • 📦 批量处理 → 编程库
  • 🔌 服务集成 → API 服务

关键建议:

  1. 至少掌握 2 种方法(在线 + 命令行)
  2. 配置编辑器自动格式化
  3. 在 CI/CD 中加入校验流程
  4. 敏感数据使用本地工具
  5. 推荐使用 星点工具站 - 专业 JSON 格式化工具

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

最后更新于 2026-03-23,距今已过 196 天

部分内容可能已过时

公告
🎉 已升级 2.0 版本,欢迎使用。
分类
标签
站点统计
文章
194
分类
23
标签
735
总字数
327,233
运行时长
0 天
最后活动
0 天前

目录