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(功能最强大)
安装方法:
# macOSbrew install jq
# Ubuntu/Debiansudo apt-get install jq
# CentOS/RHELsudo yum install jq
# Windows (使用 Chocolatey)choco install jq基本用法:
# 格式化 JSON 文件jq '.' data.json
# 格式化并保存到文件jq '.' input.json > output.json
# 美化输出(带颜色)jq '.' data.json | jq --color-output '.'
# 压缩 JSON(移除空格)jq -c '.' data.json高级技巧:
# 查询特定字段jq '.user.name' data.json
# 数组过滤jq '.users[] | select(.age > 25)' data.json
# 修改数据jq '.age = 31' data.json
# 合并多个文件jq -s 'add' file1.json file2.json2. Python json.tool
无需安装,Python 自带:
# 基本格式化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.toolPython 脚本批量处理:
#!/usr/bin/env python3import jsonimport globimport 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(无需安装):
# 快速格式化npx json < data.json
# 安装全局工具npm install -g json
# 使用 json 命令json -f data.jsonjson -f data.json name age创建自定义脚本:
#!/usr/bin/env nodeconst 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 扩展:
# 在 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 验证- 添加自定义 SchemaSublime Text
安装 Package Control 后:
# 安装 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 jsonfrom 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');});调用示例:
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 = spaceindent_size = 2end_of_line = lfcharset = utf-8trim_trailing_whitespace = trueinsert_final_newline = true2. Git 钩子自动格式化
.git/hooks/pre-commit:
#!/bin/bashfor 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 fidone3. CI/CD 集成
GitHub Actions:
name: JSON Validationon: [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 服务
关键建议:
- 至少掌握 2 种方法(在线 + 命令行)
- 配置编辑器自动格式化
- 在 CI/CD 中加入校验流程
- 敏感数据使用本地工具
- 推荐使用 星点工具站 - 专业 JSON 格式化工具
文章分享
如果这篇文章对你有帮助,欢迎分享给更多人!
最后更新于 2026-03-23,距今已过 196 天
部分内容可能已过时
相关文章 智能推荐
1
浏览器中如何格式化 JSON?5 种最简单方法(2026 教程)
实用技巧 浏览器格式化 JSON 的 5 种方法详解,无需安装任何软件。包含开发者工具、浏览器扩展、在线工具、书签脚本等,快速美化 JSON 数据。
2
JSON扁平化集成指南指南
技术教程 JSON扁平化集成指南指南
3
JSON 排序集成指南与工作流自动化
技术教程 JSON 排序集成指南,详解 Git Pre-commit、API 响应中间件、ETL 管道、CI 构建等 4 种自动化工作流集成方案。
4
JSON 语法校验完整指南 - 8 大常见错误与解决方案(2026)
教程指南 JSON 语法校验完整指南,详解 8 种常见错误类型、自动检测工具、修复方案。包含代码示例、验证工具推荐,帮助开发者快速定位并解决 JSON 语法问题。
5
JSON 转 CSV 完整指南 - 转换技巧与最佳实践(2026)
教程指南 JSON 转 CSV 完整指南,详解转换原理、嵌套数据处理、特殊字符转义。包含实战案例、性能优化技巧,帮助开发者高效完成数据转换。
随机文章 随机推荐