专业开发者必备的JSON最佳实践指南,涵盖命名规范、数据结构设计、性能优化和安全考虑。
建议使用 camelCase(JavaScript生态)或 snake_case(Python/Ruby生态),保持整个项目一致。
{
"firstName": "John",
"lastName": "Doe",
"emailAddress": "john@example.com"
}{
"FirstName": "John",
"last_name": "Doe",
"email-address": "john@example.com"
}避免使用缩写,使用完整、清晰的属性名,提高代码可读性。
{
"userId": "12345",
"createdAt": "2024-01-15",
"isEmailVerified": true
}{
"uid": "12345",
"date": "2024-01-15",
"flag": true
}避免过深的嵌套结构,建议嵌套层级不超过3层,便于访问和维护。
{
"userId": "123",
"userName": "John",
"userEmail": "john@example.com"
}{
"user": {
"id": "123",
"info": {
"name": "John",
"contact": {
"email": "john@example.com"
}
}
}
}当顺序重要时使用数组,对象属性顺序在ES6前不保证。
{
"items": [
{ "id": 1, "name": "First" },
{ "id": 2, "name": "Second" }
]
}{
"item1": { "id": 1, "name": "First" },
"item2": { "id": 2, "name": "Second" }
}在生产环境中使用压缩的JSON,减少网络传输时间和存储空间。
{"userId":"123","name":"John","email":"john@example.com"}{
"userId": "123",
"name": "John",
"email": "john@example.com"
}使用引用代替重复数据,减少数据冗余和体积。
{
"users": {
"u1": { "name": "John" },
"u2": { "name": "Jane" }
},
"groups": {
"g1": { "members": ["u1", "u2"] }
}
}{
"users": [
{ "id": "u1", "name": "John" },
{ "id": "u2", "name": "Jane" }
],
"groups": [
{
"id": "g1",
"members": [
{ "id": "u1", "name": "John" },
{ "id": "u2", "name": "Jane" }
]
}
]
}始终验证JSON输入,防止注入攻击和数据污染。
// 使用 JSON Schema 验证
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"email": {
"type": "string",
"format": "email"
}
}
}// 直接使用未验证的数据
const data = JSON.parse(userInput);
// 可能包含恶意数据不要在JSON中存储明文密码、API密钥等敏感信息。使用加密或哈希。
{
"user": {
"id": "123",
"token": "hashed_token_value"
}
}{
"user": {
"id": "123",
"password": "plain_text_password",
"apiKey": "sk-abc123xyz"
}
}为API响应添加版本号,便于向后兼容和升级
{ "version": "1.0", "data": { ... } }设计统一的错误响应格式,便于调试和处理
{ "success": false, "error": { "code": "INVALID_INPUT", "message": "..." } }统一使用ISO 8601格式的日期时间
{ "createdAt": "2024-01-15T10:30:00Z" }列表数据包含分页元数据
{ "data": [...], "pagination": { "page": 1, "total": 100 } }明确使用null表示空值,而不是省略属性
{ "middleName": null }添加新字段时保持旧字段,逐步废弃
{ "name": "John", "fullName": "John Doe" // 保留name }