DevToolBox免费
博客广告合作

JSON 格式化在线指南:美化、压缩、验证与大文件流式处理

13 分钟阅读作者 DevToolBox

TL;DR

JSON 格式化工具将紧凑的单行 JSON 转换为可读的缩进文本。在 JavaScript 中使用 JSON.stringify(obj, null, 2),在 Python 中使用 json.dumps(obj, indent=2),或在命令行中使用 jq。无需安装即可使用我们的免费 JSON 格式化工具进行即时格式化。本指南涵盖美化、压缩、验证、JSON5/JSONC、大文件流式处理、编辑器集成、CI/CD 检查、JSON Schema 和性能基准测试。 JSON Formatter Tool

Key Takeaways

  • JSON 格式化(美化打印)添加缩进和换行,但不改变数据内容。
  • JSON.stringify(obj, null, 2) 是 JavaScript 和 TypeScript 中格式化 JSON 的内置方法。
  • 压缩(Minification)去除空白字符,可将生产 API 的负载大小减少 10-30%。
  • 在线格式化工具在浏览器中提供零安装的格式化、验证和错误检测。Try it free.
  • 命令行工具如 jq 和 python -m json.tool 可即时格式化管道和文件中的 JSON。
  • JSON5 和 JSONC 允许注释和尾随逗号,但标准 JSON 不支持。
  • 对于超过 100 MB 的文件,使用流式解析器(jq --stream、Python ijson、Go json.Decoder)以避免内存问题。
  • JSON Schema 验证可捕获语法之外的结构性错误,强制执行类型、必填字段和值约束。

什么是 JSON 格式化?为什么它很重要?

JSON(JavaScript Object Notation)是 Web API、配置文件、数据库和消息队列的通用数据交换格式。当 REST API 返回响应时,JSON 负载通常是压缩的:所有空白字符都被去除以最小化带宽。

JSON 格式化(也称为 JSON 美化或 JSON 美化打印)是向原始 JSON 文本添加一致的缩进、换行和间距的过程。语义内容保持不变,只有视觉呈现发生变化。

无论你称它为 JSON 格式化器、JSON 美化器还是 JSON 美化打印器,操作都是相同的:将 JSON 字符串解析为数据结构,然后使用空白和缩进重新序列化。

→ 立即使用我们的免费 JSON 格式化工具

JSON.stringify 的缩进参数

JavaScript 和 TypeScript 提供了格式化 JSON 的内置方法。JSON.stringify() 函数接受三个参数:要序列化的值、可选的替换函数和缩进空格数。

第三个参数控制格式化。传递 2 表示两个空格缩进(最常见的约定),4 表示四个空格,或 "\t" 表示制表符缩进。

// 使用 2 空格缩进格式化 JSON
const data = {
  name: "Alice",
  age: 30,
  roles: ["admin", "developer"],
  settings: { theme: "dark", notifications: true }
};

// 2-space indent (most common)
console.log(JSON.stringify(data, null, 2));

// 4-space indent
console.log(JSON.stringify(data, null, 4));

// Tab indent
console.log(JSON.stringify(data, null, "\t"));

// 自定义替换器:隐藏敏感字段
const safeStringify = JSON.stringify(data, (key, value) => {
  if (key === "password" || key === "apiKey") return "[REDACTED]";
  return value;
}, 2);

替换器参数(第二个参数)可用于过滤输出。你可以传递属性名数组来仅包含特定键,或传递函数在序列化期间转换值。

压缩与美化的权衡

压缩和美化是同一枚硬币的两面。理解何时使用每种方式对构建高效系统至关重要。

美化的 JSON 具有缩进和换行,便于人类阅读。适用于开发、调试、日志记录、配置文件和代码审查。代价是字节大小增加 10-30%。

压缩的 JSON 去除所有不必要的空白。适用于生产 API 响应、数据库存储、消息队列和网络传输。

在实践中,大多数系统在传输时压缩 JSON,按需为人类消费美化它。

// 压缩 JSON(无空白)
const minified = JSON.stringify(data);
// {"name":"Alice","age":30,"roles":["admin","developer"],...}

// 解析并重新格式化 JSON 字符串
const raw = '{"name":"Alice","age":30}';
const parsed = JSON.parse(raw);
const pretty = JSON.stringify(parsed, null, 2);
/*
{
  "name": "Alice",
  "age": 30
}
*/

在线 JSON 格式化工具 vs 命令行工具

格式化 JSON 有两种主要方法:基于浏览器的在线工具和命令行工具。

在线格式化工具无需安装。粘贴 JSON,即时获得格式化输出。通常包括语法验证、错误高亮、可自定义缩进和一键复制。

→ 在浏览器中格式化 JSON

命令行工具集成到现有工作流中。最流行的两个是 jq 和 Python:

jq 是命令行上的 JSON 瑞士军刀。运行 jq . file.json 进行带语法高亮的美化打印。

# Pretty-print with jq (color-coded output)
jq . data.json

# Minify with jq
jq -c . data.json

# Extract a specific field
jq '.users[0].name' data.json

# Filter array elements
jq '.items[] | select(.price > 10)' data.json

# Pretty-print with Python (no install needed)
python3 -m json.tool data.json

# Pipe from curl to jq
curl -s https://api.example.com/users | jq .

# Validate JSON (exit code 0 = valid, non-zero = invalid)
jq empty config.json && echo "Valid" || echo "Invalid"

python -m json.tool 随每个 Python 安装附带。运行 cat file.json | python3 -m json.tool 一步完成格式化和验证。

其他值得一提的工具:fx(交互式 JSON 浏览器)、gron(使 JSON 可 grep)和 jless(终端 JSON 查看器)。

JSON 验证:语法错误、尾随逗号和注释

有效的 JSON 必须遵循 RFC 8259 定义的严格语法规则。破坏 JSON 解析的常见错误包括:

  • 对象或数组最后一个元素后的尾随逗号
  • 使用单引号而非双引号
  • 未加引号的键名
  • 注释:JSON 不支持 // 或 /* */ 注释
  • 根值后的尾随字符
  • NaN、Infinity 和 undefined 不是有效的 JSON 值
  • 十六进制数:0xFF 不是有效的 JSON

当你将无效 JSON 粘贴到格式化工具中时,工具应报告确切的错误位置。我们的 JSON 格式化工具会自动验证并内联高亮错误。

// Common JSON syntax errors and their fixes

// ERROR: Trailing comma
// { "a": 1, "b": 2, }   <-- trailing comma after 2
// FIX:
{ "a": 1, "b": 2 }

// ERROR: Single quotes
// { 'name': 'Alice' }
// FIX:
{ "name": "Alice" }

// ERROR: Unquoted keys
// { name: "Alice" }
// FIX:
{ "name": "Alice" }

// ERROR: Comments
// { "debug": true  // enable debug mode }
// FIX: Remove comments or use JSONC/JSON5
{ "debug": true }

// ERROR: JavaScript values
// { "value": undefined, "count": NaN, "max": Infinity }
// FIX:
{ "value": null, "count": 0, "max": 999999 }

JSON5 和 JSONC(带注释的 JSON)

标准 JSON 的严格规则给需要人类可读性的配置文件带来了摩擦。两个扩展解决了这个问题:

JSONC(带注释的 JSON)添加了对单行和多行注释以及尾随逗号的支持。VS Code 将 JSONC 用于其设置文件。

JSON5 是 JSON 的超集,添加了注释、尾随逗号、单引号字符串、未加引号的对象键等功能。

// JSONC example (VS Code settings, tsconfig.json)
{
  // This is a single-line comment
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "strict": true, // trailing comma allowed in JSONC
  },
  /* Multi-line comment
     explaining the configuration */
  "include": ["src/**/*"],
}

// JSON5 example (more relaxed syntax)
{
  name: 'DevToolBox',       // unquoted keys, single quotes
  version: 2,
  features: [
    'formatting',
    'validation',
    'minification',         // trailing comma
  ],
  config: {
    maxFileSize: 0xFF,      // hexadecimal numbers
    ratio: .5,              // leading decimal point
    debug: true,
  },
}

虽然这些格式便于配置,但它们不能与标准 JSON 互换。API 端点应始终返回严格的 JSON。

格式化大型 JSON 文件:流式处理和内存

标准 JSON 解析器在处理前将整个文件加载到内存中。对于超过 100 MB 的文件,你需要流式处理方法:

jq --stream:以路径-值对流的方式处理 JSON,无需加载整个文档。

Python ijson:一次产出一个项目的迭代式 JSON 解析器。使用恒定内存处理数百万条记录。

# jq streaming: extract names from a huge array
jq --stream 'select(.[0][-1] == "name") | .[1]' huge.json

# Python ijson: iterate over items with constant memory
import ijson

with open("huge.json", "rb") as f:
    for item in ijson.items(f, "users.item"):
        print(item["name"])

# Node.js stream-json: process large JSON files
const { parser } = require("stream-json");
const { streamArray } = require("stream-json/streamers/StreamArray");
const fs = require("fs");

fs.createReadStream("huge.json")
  .pipe(parser())
  .pipe(streamArray())
  .on("data", ({ value }) => {
    console.log(value.name);
  });

Go encoding/json Decoder:Go 标准库提供增量读取令牌的解码器。

Node.js 流:stream-json 和 JSONStream 等库以 Node.js 流的方式处理 JSON。

经验法则:如果 JSON 文件大于可用 RAM 的 25%,使用流式解析器。

在 VS Code、IntelliJ 和 Vim 中格式化 JSON

每个主流代码编辑器都提供内置或基于插件的 JSON 格式化。

VS Code:打开 .json 文件按 Shift+Alt+F 格式化。支持语法高亮、括号匹配、折叠和内联错误检测。

IntelliJ IDEA:按 Ctrl+Alt+L 重新格式化。支持 JSON Schema 映射和自动补全。

Vim:使用 :%!jq . 通过 jq 格式化整个缓冲区,或使用 :%!python3 -m json.tool

Sublime Text:命令面板中选择 "Pretty Print (JSON)"。处理大文件性能优异。

# VS Code keyboard shortcuts for JSON
# Format document:     Shift+Alt+F (Win/Linux) / Shift+Option+F (Mac)
# Fold all:            Ctrl+K Ctrl+0
# Unfold all:          Ctrl+K Ctrl+J
# Toggle word wrap:    Alt+Z

# Vim: format entire buffer with jq
:%!jq .

# Vim: format with Python
:%!python3 -m json.tool

# Vim: format selected lines with jq
:'<,'>!jq .

CI/CD 流水线中的 JSON 检查

在 CI/CD 流水线中自动化 JSON 验证可在配置错误到达生产环境之前捕获它们。

GitHub Actions:在工作流步骤中使用 jq 验证 JSON 文件。

# GitHub Actions: validate all JSON files
name: Validate JSON
on: [push, pull_request]
jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Validate JSON files
        run: |
          find . -name "*.json" -not -path "./node_modules/*" | while read f; do
            jq empty "$f" || { echo "Invalid JSON: $f"; exit 1; }
          done

# Pre-commit hook (.pre-commit-config.yaml)
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: check-json
      - id: pretty-format-json
        args: [--autofix, --indent, "2"]

# Node.js one-liner validation
node -e "JSON.parse(require('fs').readFileSync('config.json','utf8'))"

# Python validation with error details
python3 -c "
import json, sys
try:
    json.load(open(sys.argv[1]))
    print('Valid JSON')
except json.JSONDecodeError as e:
    print(f'Invalid: {e}')
    sys.exit(1)
" config.json

Pre-commit hooks:使用 check-json hook 在每次提交时验证所有 JSON 文件。

ESLint:eslint-plugin-json 将 JSON 验证集成到现有的 lint 设置中。

自定义脚本:简单的 Node.js 单行命令即可验证 JSON。

JSON Schema 验证

JSON Schema 超越语法验证。它定义了 JSON 数据的预期结构:属性、类型、必填字段、值约束和嵌套结构。

JSON Schema 本身是一个 JSON 文档,使用 type、properties、required、items 等关键字表达约束。

// JSON Schema example
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["name", "email", "age"],
  "properties": {
    "name": {
      "type": "string",
      "minLength": 1,
      "maxLength": 100
    },
    "email": {
      "type": "string",
      "format": "email"
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    },
    "roles": {
      "type": "array",
      "items": { "type": "string", "enum": ["admin", "user", "editor"] },
      "minItems": 1,
      "uniqueItems": true
    }
  },
  "additionalProperties": false
}

// JavaScript: validate with Ajv
import Ajv from "ajv";
import addFormats from "ajv-formats";

const ajv = new Ajv();
addFormats(ajv);

const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) {
  console.error(validate.errors);
}

# Python: validate with jsonschema
from jsonschema import validate, ValidationError

try:
    validate(instance=data, schema=schema)
    print("Valid")
except ValidationError as e:
    print(f"Invalid: {e.message}")

流行的验证库包括 Ajv(JavaScript)、jsonschema(Python)和 gojsonschema(Go)。

JSON Schema 广泛用于 API 文档(OpenAPI/Swagger)、表单生成、配置验证和数据管道约定。

大型 JSON 文件性能基准测试

不同 JSON 解析器和语言的性能差异巨大。以下是在现代硬件上解析 100 MB JSON 文件的近似基准:

另请参阅:JSON Viewer

解析器解析时间峰值内存
simdjson (C++/Rust)~120 ms~200 MB
Go encoding/json~800 ms~350 MB
Python json (CPython)~3,500 ms~600 MB
Node.js JSON.parse~400 ms~400 MB
jq (streaming)~2,000 ms~50 MB
Python ijson (streaming)~5,000 ms~30 MB

关键洞察:流式解析器以更高的总处理时间为代价,显著减少内存使用。

格式化步骤(重新序列化为缩进文本)通常在解析时间的基础上增加 20-40%。

代码示例:JavaScript / TypeScript

// 使用 2 空格缩进格式化 JSON
const obj = { name: "Alice", age: 30, roles: ["admin", "dev"] };
const formatted = JSON.stringify(obj, null, 2);
console.log(formatted);

// 按字母顺序排序键
const sortedKeys = JSON.stringify(obj, Object.keys(obj).sort(), 2);

// 自定义替换器:隐藏敏感字段
function safeStringify(data) {
  return JSON.stringify(data, (key, value) => {
    const sensitiveKeys = ["password", "secret", "apiKey", "token"];
    if (sensitiveKeys.includes(key)) return "[REDACTED]";
    return value;
  }, 2);
}

// 压缩 JSON(无空白)
const minified = JSON.stringify(obj);

// 解析并重新格式化 JSON 字符串
function formatJson(jsonString) {
  try {
    const parsed = JSON.parse(jsonString);
    return { success: true, result: JSON.stringify(parsed, null, 2) };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

// Format JSON in Node.js from a file
const fs = require("fs");
const raw = fs.readFileSync("data.json", "utf8");
const pretty = JSON.stringify(JSON.parse(raw), null, 2);
fs.writeFileSync("data-formatted.json", pretty);

代码示例:Python

import json

# 使用 2 空格缩进和排序键格式化 JSON
data = {"name": "Alice", "age": 30, "roles": ["admin", "dev"]}
formatted = json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False)
print(formatted)

# 读取、格式化并写入 JSON 文件
with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

with open("data-formatted.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

# 从标准输入验证 JSON
import sys

def validate_json(filepath):
    try:
        with open(filepath, "r", encoding="utf-8") as f:
            json.load(f)
        print(f"{filepath}: Valid JSON")
        return True
    except json.JSONDecodeError as e:
        print(f"{filepath}: Invalid JSON at line {e.lineno}, col {e.colno}")
        print(f"  Error: {e.msg}")
        return False

# 压缩 JSON 文件
def minify_json(input_path, output_path):
    with open(input_path, "r", encoding="utf-8") as f:
        data = json.load(f)
    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(data, f, separators=(",", ":"), ensure_ascii=False)

# Command-line usage:
# python3 -m json.tool input.json > formatted.json
# python3 -m json.tool --compact input.json > minified.json

代码示例:Go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "os"
)

// 使用缩进格式化 JSON
func formatJSON(input []byte) (string, error) {
    var buf bytes.Buffer
    err := json.Indent(&buf, input, "", "  ")
    if err != nil {
        return "", fmt.Errorf("invalid JSON: %w", err)
    }
    return buf.String(), nil
}

// 大文件流式解码器
func streamLargeJSON(filename string) error {
    f, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer f.Close()

    decoder := json.NewDecoder(f)

    // Read opening bracket
    _, err = decoder.Token()
    if err != nil {
        return err
    }

    // Read array elements one by one
    for decoder.More() {
        var item map[string]interface{}
        if err := decoder.Decode(&item); err != nil {
            return err
        }
        fmt.Printf("Name: %s\n", item["name"])
    }

    return nil
}

func main() {
    raw := []byte(`{"name":"Alice","age":30,"roles":["admin","dev"]}`)
    formatted, err := formatJSON(raw)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %v\n", err)
        os.Exit(1)
    }
    fmt.Println(formatted)
}

常见问题

JSON 格式化器和 JSON 验证器有什么区别?

JSON 格式化器添加缩进和换行使 JSON 可读。JSON 验证器检查 JSON 是否符合正确的语法规则。大多数在线工具两者兼备:尝试解析输入,报告无效错误,有效则格式化输出。

格式化会改变 JSON 数据吗?

不会。格式化只添加或删除空白字符。语义内容完全相同。压缩的 JSON 和美化后的版本解析为完全相同的数据结构。

JSON 应该使用什么缩进大小?

两个空格是最常见的约定,大多数工具默认使用。四个空格也很流行。选择一种并在项目中保持一致。

JSON 可以有注释吗?

标准 JSON(RFC 8259)不支持注释。但 JSONC 允许 // 和 /* */ 注释,VS Code 的设置文件和 TypeScript 的 tsconfig.json 使用 JSONC。JSON5 也支持注释。

如何格式化大型 JSON 文件而不耗尽内存?

使用流式解析器。命令行上 jq --stream 无需加载整个文件即可处理。Python 中 ijson 库使用恒定内存迭代解析。Node.js 中 stream-json 包以流方式处理。

在 CI 流水线中验证 JSON 最快的方法是什么?

最简单的方法是单行命令:Node.js 中使用 JSON.parse,Python 中使用 python3 -m json.tool,或使用 jq。对于基于 Schema 的验证,使用 Ajv 或 jsonschema。

JSON5 与标准 JSON 兼容吗?

JSON5 是 JSON 的超集:每个有效的 JSON 文档也是有效的 JSON5。但 JSON5 的注释、尾随逗号等特性不是有效的标准 JSON。JSON5 设计用于配置文件。

JSON 格式化工具如何处理 Unicode 和特殊字符?

JSON 需要 UTF-8 编码。格式化工具按原样保留所有 Unicode 字符。非 ASCII 字符可选择转义为 \uXXXX 序列。大多数现代格式化工具保留 Unicode 字符不转义。

总结

JSON 格式化是一项基本的开发者技能,可以提高可读性、调试速度和协作效率。无论使用在线工具快速格式化、jq 进行命令行工作流,还是 JSON.stringify 进行编程格式化,关键是为机器保持 JSON 压缩,为人类保持美化。

使用我们的免费在线 JSON 格式化工具格式化、验证和压缩您的 JSON。

这篇文章有帮助吗?

保持更新

获取每周开发技巧和新工具通知。

无垃圾邮件,随时退订。

合作推荐

赞助这篇文章

把你的产品放到这个开发者主题旁边,并追踪点击效果。

咨询文章赞助

相关文章

JSON 格式化工具完全指南:在线美化、VS Code、命令行与代码中格式化 JSON(2026)

学习如何在线格式化 JSON、在 VS Code 中美化 JSON、用命令行工具 jq 处理 JSON,以及在 JavaScript 和 Python 中进行 JSON 格式化。涵盖验证、压缩、查看器和常见错误。

如何打开 JSON 文件:开发者完全指南

学习如何在 VS Code、浏览器、终端(cat/jq)、Notepad++、Python、Node.js 和在线工具中打开 JSON 文件。

JSON Schema 完全指南:验证、类型和最佳实践

从基础到高级掌握 JSON Schema:定义类型、验证规则、$ref 引用和条件模式。

JSON vs YAML vs TOML:你应该用哪种配置格式?

比较 JSON、YAML 和 TOML 配置格式,了解语法、特性和优缺点,选择适合你项目的格式。

本站使用 Cookie 进行流量分析与广告展示。继续浏览即视为同意。 隐私政策