Toolypet
返回博客
Dev

JSON Formatter & Validator 实战指南 - 从调试到验证

API响应读不懂?通过实战示例掌握JSON格式化、验证以及常见语法错误的解决方法。

Toolypet Team

Toolypet Team

Development Team

4 分钟阅读

JSON Formatter & Validator 实战指南

"这个API响应...完全看不懂哪是哪。"

你收到过压缩成一行的JSON响应吗?在3000字符的嵌套对象中找特定字段简直是噩梦。

JSON Formatter解决这个问题。而Validator回答"为什么解析失败?"这个问题。


JSON 30秒回顾

数据类型

{
  "string": "文本",
  "number": 42,
  "boolean": true,
  "null": null,
  "array": [1, 2, 3],
  "object": {"nested": "value"}
}

核心规则(常见错误)

规则正确错误
键引号{"name": "值"}{name: "值"}
字符串"双引号"'单引号'
尾随逗号"a": 1}"a": 1,}
注释不允许// comment

Minified vs Prettified

实际收到的API响应(Minified)

{"users":[{"id":1,"name":"张三","email":"zhangsan@dev.com","profile":{"avatar":"https://cdn.example.com/1.jpg","bio":"全栈开发者"}}],"pagination":{"total":150,"page":1,"limit":10}}

你能读懂吗?

Formatter处理后(Prettified)

{
  "users": [
    {
      "id": 1,
      "name": "张三",
      "email": "zhangsan@dev.com",
      "profile": {
        "avatar": "https://cdn.example.com/1.jpg",
        "bio": "全栈开发者"
      }
    }
  ],
  "pagination": {
    "total": 150,
    "page": 1,
    "limit": 10
  }
}

结构一目了然。 你可以立即找到users[0].profile.bio在哪里。


5个常见JSON错误

1. Trailing Comma(尾随逗号)

最常见的错误。JavaScript允许,但在JSON中是错误

// 错误: Unexpected token }
{
  "name": "张三",
  "age": 30,
}

// 修正
{
  "name": "张三",
  "age": 30
}

2. 单引号

// 错误: Unexpected token '
{'name': '张三'}

// 修正
{"name": "张三"}

3. 没有引号的键

// 错误: Unexpected token n
{name: "张三"}

// 修正
{"name": "张三"}

4. 未转义的字符

// 错误: 换行、制表符等
{"message": "你好
世界"}

// 修正
{"message": "你好\n世界"}
字符转义
换行\n
制表符\t
反斜杠\\
双引号\"

5. 错误的数字格式

// 错误
{"value": 007}       // 前导零
{"hex": 0xFF}        // 十六进制

// 修正
{"value": 7}
{"hex": "0xFF"}      // 作为字符串

实战:代码中格式化

JavaScript

// 调试API响应
fetch('/api/users')
  .then(res => res.json())
  .then(data => {
    // 在控制台中易于阅读
    console.log(JSON.stringify(data, null, 2));
  });

JSON.stringify(data, null, 2)的第三个参数:

  • 2:2个空格缩进
  • 4:4个空格缩进
  • '\t':制表符缩进

提取特定字段

const user = {
  id: 1,
  name: "张三",
  password: "secret123",
  email: "zhangsan@dev.com"
};

// 排除password输出
console.log(JSON.stringify(user, ['id', 'name', 'email'], 2));

输出:

{
  "id": 1,
  "name": "张三",
  "email": "zhangsan@dev.com"
}

命令行处理JSON

jq - JSON处理的瑞士军刀

# 安装
brew install jq      # macOS
apt install jq       # Ubuntu

# 格式化
cat response.json | jq .

# 提取特定字段
cat response.json | jq '.users[0].name'

# 过滤数组
cat response.json | jq '.users[] | select(.age > 30)'

# 选择字段创建新对象
cat response.json | jq '.users[] | {name, email}'

Python

# 验证 + 格式化文件
python -m json.tool data.json

# 通过管道处理
curl https://api.example.com/users | python -m json.tool

Node.js

# 检查文件是否为有效JSON
node -e "require('./data.json')"

用JSON Schema验证结构

超越简单的语法检查,可以验证数据结构和类型

Schema定义

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "required": ["name", "email"],
  "properties": {
    "name": {
      "type": "string",
      "minLength": 2,
      "maxLength": 50
    },
    "email": {
      "type": "string",
      "format": "email"
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    }
  }
}

在JavaScript中验证(ajv)

import Ajv from 'ajv';
import addFormats from 'ajv-formats';

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

const validate = ajv.compile(schema);

const data = {
  name: "张三",
  email: "invalid-email",
  age: -5
};

if (!validate(data)) {
  console.log(validate.errors);
  // [
  //   { keyword: 'format', message: 'must match format "email"' },
  //   { keyword: 'minimum', message: 'must be >= 0' }
  // ]
}

IDE/编辑器设置

VSCode

# 自动格式化快捷键
Windows/Linux: Shift + Alt + F
Mac: Shift + Option + F

# 保存时自动格式化(settings.json)
"[json]": {
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode"
}

JetBrains(IntelliJ、WebStorm)

# 自动格式化
Windows/Linux: Ctrl + Alt + L
Mac: Cmd + Option + L

FAQ

Q: 我想在JSON中写注释

A: 标准JSON不支持注释。替代方案:

  1. JSONC(JSON with Comments):用于VSCode配置文件等
  2. JSON5:允许注释、尾随逗号、单引号
  3. 单独字段"_comment": "说明"
{
  "_comment": "此配置用于开发环境",
  "debug": true
}

Q: 大型JSON文件打不开

A: 普通编辑器处理几十MB的文件会卡死。替代方案:

  • jq:流式处理
  • fx:终端交互式查看器(npm i -g fx
  • 在线工具:专用大型JSON查看器

Q: 能不能把整个API响应都打日志?

A: 在生产环境中很危险。

// 错误:可能暴露敏感信息
console.log(JSON.stringify(apiResponse));

// 正确:屏蔽敏感字段
const sanitize = (obj) => JSON.stringify(obj, (key, val) =>
  ['password', 'token', 'secret'].includes(key) ? '***' : val
);

总结

情况解决方案
API响应难以阅读用Formatter缩进
解析错误用Validator检查语法
重复出现的错误检查尾随逗号、引号
结构验证使用JSON Schema
CLI处理使用jq

相关工具

工具用途
JSON Formatter格式化/压缩
JSON Validator语法验证
JSON to CSV格式转换
JSONformattervalidatorAPI开发工具调试

关于作者

Toolypet Team

Toolypet Team

Development Team

The Toolypet Team creates free, privacy-focused web tools for developers and designers. All tools run entirely in your browser with no data sent to servers.

Web DevelopmentCSS ToolsDeveloper ToolsSEOSecurity