json-style

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

JSON Style Guide

JSON风格指南

Apply Google's JSON Style Guide conventions for consistent, well-structured JSON APIs and data formats.
遵循Google的JSON风格指南规范,创建一致、结构清晰的JSON API与数据格式。

Overview

概述

This skill provides guidelines for creating JSON APIs and data structures following Google's JSON Style Guide. The guide clarifies naming conventions, property structures, reserved property names, and standard patterns for JSON requests and responses in both RPC-based and REST-based APIs.
本Skill提供遵循Google JSON风格指南的JSON API与数据结构创建准则。该指南明确了RPC和REST风格API中JSON请求与响应的命名规范、属性结构、保留属性名称及标准模式。

Core Principles

核心原则

Use Double Quotes

使用双引号

All property names must be surrounded by double quotes. String values must use double quotes. Other value types (boolean, number, null, arrays, objects) should not be quoted.
json
{
  "propertyName": "string value",
  "count": 42,
  "isActive": true,
  "data": null
}
所有属性名称必须用双引号包裹。字符串值必须使用双引号。其他值类型(布尔值、数字、null、数组、对象)不应加引号。
json
{
  "propertyName": "string value",
  "count": 42,
  "isActive": true,
  "data": null
}

No Comments

禁止注释

Do not include comments in JSON objects. JSON does not support comments in the specification.
JSON对象中不得包含注释。JSON规范本身不支持注释。

Flatten Data Appropriately

合理扁平化数据

Data should be flattened unless there is a clear semantic reason for structured hierarchy. Group properties only when they represent a single logical structure.
Structured (preferred for related data):
json
{
  "company": "Google",
  "address": {
    "line1": "111 8th Ave",
    "city": "New York",
    "state": "NY",
    "zip": "10011"
  }
}
除非有明确的语义原因需要结构化层级,否则应将数据扁平化。仅当属性代表单一逻辑结构时才进行分组。
结构化(推荐用于关联数据):
json
{
  "company": "Google",
  "address": {
    "line1": "111 8th Ave",
    "city": "New York",
    "state": "NY",
    "zip": "10011"
  }
}

Property Naming

属性命名

Naming Format

命名格式

Property names must:
  • Be meaningful with defined semantics
  • Use camelCase (not snake_case or PascalCase)
  • Start with a letter, underscore (_), or dollar sign ($)
  • Contain only letters, digits, underscores, or dollar signs
  • Avoid JavaScript reserved keywords
json
{
  "firstName": "John",
  "lastName": "Doe",
  "accountBalance": 1000.50,
  "isVerified": true
}
属性名称必须:
  • 具备明确语义,名称有意义
  • 使用camelCase(而非snake_case或PascalCase)
  • 以字母、下划线(_)或美元符号($)开头
  • 仅包含字母、数字、下划线或美元符号
  • 避免使用JavaScript保留关键字
json
{
  "firstName": "John",
  "lastName": "Doe",
  "accountBalance": 1000.50,
  "isVerified": true
}

Singular vs Plural

单复数规则

Use plural names for arrays. Use singular names for all other properties.
json
{
  "author": "lisa",
  "siblings": ["bart", "maggie"],
  "totalItems": 10,
  "itemCount": 10
}
数组使用复数名称。其他所有属性使用单数名称。
json
{
  "author": "lisa",
  "siblings": ["bart", "maggie"],
  "totalItems": 10,
  "itemCount": 10
}

JSON Maps vs Objects

JSON映射与对象

When using a JSON object as a map (associative array), keys can use any Unicode characters. Map keys do not need to follow property naming guidelines.
json
{
  "address": {
    "addressLine1": "123 Anystreet",
    "city": "Anytown"
  },
  "thumbnails": {
    "72": "https://url.to.72px.thumbnail",
    "144": "https://url.to.144px.thumbnail"
  }
}
当JSON对象用作映射(关联数组)时,键可以使用任意Unicode字符。映射键无需遵循属性命名准则。
json
{
  "address": {
    "addressLine1": "123 Anystreet",
    "city": "Anytown"
  },
  "thumbnails": {
    "72": "https://url.to.72px.thumbnail",
    "144": "https://url.to.144px.thumbnail"
  }
}

Property Values

属性值

Valid Value Types

有效值类型

Property values must be:
  • Boolean:
    true
    or
    false
  • Number: integers or floating-point
  • String: Unicode strings in double quotes
  • Object:
    {}
  • Array:
    []
  • Null:
    null
JavaScript expressions and functions are not allowed.
属性值必须为以下类型之一:
  • 布尔值:
    true
    false
  • 数字:整数或浮点数
  • 字符串:双引号包裹的Unicode字符串
  • 对象:
    {}
  • 数组:
    []
  • Null:
    null
不允许使用JavaScript表达式和函数。

Empty or Null Values

空值或Null值

Consider removing properties with empty or null values unless there is a strong semantic reason. A property with value
0
,
false
, or
""
may have semantic meaning and should be kept.
json
{
  "volume": 10,
  "balance": 0,
  "currentlyPlaying": null
}
Better:
json
{
  "volume": 10,
  "balance": 0
}
除非有强烈的语义需求,否则应移除值为空或null的属性。值为
0
false
""
的属性可能具备语义意义,应予以保留。
json
{
  "volume": 10,
  "balance": 0,
  "currentlyPlaying": null
}
优化后:
json
{
  "volume": 10,
  "balance": 0
}

Enum Values

枚举值

Represent enums as strings (not numbers) to handle graceful changes as APIs evolve.
json
{
  "color": "WHITE",
  "status": "ACTIVE"
}
枚举值以字符串形式表示(而非数字),以便在API演进时实现平滑变更。
json
{
  "color": "WHITE",
  "status": "ACTIVE"
}

Standard Data Types

标准数据类型

Dates

日期

Format dates according to RFC 3339:
json
{
  "lastUpdate": "2007-11-06T16:34:41.000Z",
  "createdAt": "2024-02-19T10:30:00.000Z"
}
日期格式遵循RFC 3339规范:
json
{
  "lastUpdate": "2007-11-06T16:34:41.000Z",
  "createdAt": "2024-02-19T10:30:00.000Z"
}

Time Durations

时长

Format durations according to ISO 8601:
json
{
  "duration": "P3Y6M4DT12H30M5S"
}
时长格式遵循ISO 8601规范:
json
{
  "duration": "P3Y6M4DT12H30M5S"
}

Latitude/Longitude

经纬度

Format coordinates according to ISO 6709 using ±DD.DDDD±DDD.DDDD degrees format:
json
{
  "location": "+40.6894-074.0447"
}
坐标格式遵循ISO 6709规范,使用±DD.DDDD±DDD.DDDD度数格式:
json
{
  "location": "+40.6894-074.0447"
}

Standard JSON Structure

标准JSON结构

Top-Level Properties

顶层属性

A JSON response should have these optional top-level properties:
  • apiVersion
    - Version of the API (string)
  • context
    - Client-set value echoed by server (string)
  • id
    - Server-assigned response identifier (string)
  • method
    - Operation performed (string)
  • params
    - Input parameters for RPC requests (object)
  • data
    - Container for successful response data (object)
  • error
    - Error details if request failed (object)
A response should contain either
data
or
error
, but not both.
json
{
  "apiVersion": "2.1",
  "data": {
    "kind": "user",
    "id": "12345",
    "name": "John Doe"
  }
}
JSON响应可包含以下可选顶层属性:
  • apiVersion
    - API版本(字符串)
  • context
    - 客户端设置、服务器回显的值(字符串)
  • id
    - 服务器分配的响应标识符(字符串)
  • method
    - 执行的操作(字符串)
  • params
    - RPC请求的输入参数(对象)
  • data
    - 成功响应数据的容器(对象)
  • error
    - 请求失败时的错误详情(对象)
响应中应仅包含
data
error
中的一个,不可同时存在。
json
{
  "apiVersion": "2.1",
  "data": {
    "kind": "user",
    "id": "12345",
    "name": "John Doe"
  }
}

Data Object Properties

数据对象属性

Common properties in the
data
object:
  • kind
    - Type of object (should be first property)
  • fields
    - Fields present in partial response
  • etag
    - Entity tag for versioning
  • id
    - Unique identifier
  • lang
    - Language code (BCP 47)
  • updated
    - Last update timestamp (RFC 3339)
  • deleted
    - Boolean marker for deleted entries
  • items
    - Array of items (should be last property)
data
对象中的常见属性:
  • kind
    - 对象类型(应作为第一个属性)
  • fields
    - 部分响应中包含的字段
  • etag
    - 用于版本控制的实体标签
  • id
    - 唯一标识符
  • lang
    - 语言代码(BCP 47)
  • updated
    - 最后更新时间戳(RFC 3339)
  • deleted
    - 标记条目是否已删除的布尔值
  • items
    - 项目数组(应作为最后一个属性)

Pagination Properties

分页属性

For paginated data in the
data
object:
  • currentItemCount
    - Number of items in current response
  • itemsPerPage
    - Requested page size
  • startIndex
    - Index of first item (1-based)
  • totalItems
    - Total available items
  • pageIndex
    - Current page number (1-based)
  • totalPages
    - Total number of pages
  • pagingLinkTemplate
    - URI template for pagination
data
对象中用于分页数据的属性:
  • currentItemCount
    - 当前响应中的项目数量
  • itemsPerPage
    - 请求的页面大小
  • startIndex
    - 第一个项目的索引(从1开始)
  • totalItems
    - 可用项目总数
  • pageIndex
    - 当前页码(从1开始)
  • totalPages
    - 总页数
  • pagingLinkTemplate
    - 分页用的URI模板

Link Properties

链接属性

Link properties in the
data
object:
  • self
    /
    selfLink
    - Link to retrieve this resource
  • edit
    /
    editLink
    - Link to update/delete this resource
  • next
    /
    nextLink
    - Link to next page
  • previous
    /
    previousLink
    - Link to previous page
data
对象中的链接属性:
  • self
    /
    selfLink
    - 获取此资源的链接
  • edit
    /
    editLink
    - 更新/删除此资源的链接
  • next
    /
    nextLink
    - 下一页的链接
  • previous
    /
    previousLink
    - 上一页的链接

Error Object Properties

错误对象属性

When an error occurs, use the
error
object:
  • code
    - HTTP status code (integer)
  • message
    - Human-readable error message (string)
  • errors
    - Array of error details (array)
Each error in
errors
array can have:
  • domain
    - Service identifier
  • reason
    - Error type identifier
  • message
    - Detailed error message
  • location
    - Where error occurred
  • locationType
    - How to interpret location
  • extendedHelp
    - URI to help documentation
  • sendReport
    - URI to error report form
json
{
  "apiVersion": "2.0",
  "error": {
    "code": 404,
    "message": "File Not Found",
    "errors": [{
      "domain": "Calendar",
      "reason": "ResourceNotFoundException",
      "message": "File Not Found"
    }]
  }
}
发生错误时,使用
error
对象:
  • code
    - HTTP状态码(整数)
  • message
    - 易读的错误信息(字符串)
  • errors
    - 错误详情数组(数组)
errors
数组中的每个错误可包含:
  • domain
    - 服务标识符
  • reason
    - 错误类型标识符
  • message
    - 详细错误信息
  • location
    - 错误发生位置
  • locationType
    - 位置的解释方式
  • extendedHelp
    - 帮助文档的URI
  • sendReport
    - 错误报告表单的URI
json
{
  "apiVersion": "2.0",
  "error": {
    "code": 404,
    "message": "File Not Found",
    "errors": [{
      "domain": "Calendar",
      "reason": "ResourceNotFoundException",
      "message": "File Not Found"
    }]
  }
}

Property Ordering

属性顺序

While property order is not enforced by JSON, certain orderings improve parsing efficiency:
  1. kind
    should be first
    - Helps parsers determine object type early
  2. items
    should be last in
    data
    - Allows reading collection metadata before parsing items
json
{
  "data": {
    "kind": "album",
    "title": "My Photo Album",
    "totalItems": 100,
    "items": [
      {
        "kind": "photo",
        "title": "My First Photo"
      }
    ]
  }
}
虽然JSON不强制要求属性顺序,但特定顺序可提升解析效率:
  1. kind
    应置于首位
    - 帮助解析器尽早确定对象类型
  2. items
    应置于
    data
    对象的末尾
    - 允许在解析项目前读取集合元数据
json
{
  "data": {
    "kind": "album",
    "title": "My Photo Album",
    "totalItems": 100,
    "items": [
      {
        "kind": "photo",
        "title": "My First Photo"
      }
    ]
  }
}

Quick Reference

快速参考

Naming Checklist

命名检查清单

  • Use camelCase for property names
  • Use plural names for arrays
  • Use singular names for other properties
  • Avoid JavaScript reserved keywords
  • Choose meaningful, semantic names
  • 属性名称使用camelCase
  • 数组使用复数名称
  • 其他属性使用单数名称
  • 避免使用JavaScript保留关键字
  • 选择有意义、具备语义的名称

Value Type Checklist

值类型检查清单

  • Use strings for enum values
  • Format dates as RFC 3339
  • Format durations as ISO 8601
  • Remove null/empty values unless semantically meaningful
  • Use appropriate types (boolean, number, string, object, array, null)
  • 枚举值使用字符串类型
  • 日期格式遵循RFC 3339
  • 时长格式遵循ISO 8601
  • 移除null/空值(除非具备语义意义)
  • 使用合适的类型(布尔值、数字、字符串、对象、数组、null)

Structure Checklist

结构检查清单

  • Include
    apiVersion
    in responses
  • Use
    data
    for success,
    error
    for failures (not both)
  • Place
    kind
    first in objects
  • Place
    items
    last in
    data
    object
  • Use reserved property names for standard semantics
  • 响应中包含
    apiVersion
  • 成功响应使用
    data
    ,失败响应使用
    error
    (不可同时使用)
  • kind
    置于对象首位
  • items
    置于
    data
    对象末尾
  • 为标准语义使用保留属性名称

Additional Resources

额外资源

Reference Files

参考文件

For detailed specifications:
  • references/naming-conventions.md
    - Complete naming rules and reserved keywords
  • references/reserved-properties.md
    - Full list of reserved property names and their semantics
  • references/pagination-patterns.md
    - Detailed pagination implementation patterns
如需详细规范,请查看:
  • references/naming-conventions.md
    - 完整的命名规则与保留关键字
  • references/reserved-properties.md
    - 保留属性名称及其语义的完整列表
  • references/pagination-patterns.md
    - 详细的分页实现模式

Example Files

示例文件

Working examples in
examples/
:
  • examples/api-response.json
    - Standard API response structure
  • examples/error-response.json
    - Error handling example
  • examples/paginated-response.json
    - Pagination example with all properties
examples/
目录下的实用示例:
  • examples/api-response.json
    - 标准API响应结构
  • examples/error-response.json
    - 错误处理示例
  • examples/paginated-response.json
    - 包含所有属性的分页示例