json-style
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseJSON 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: or
truefalse - Number: integers or floating-point
- String: Unicode strings in double quotes
- Object:
{} - Array:
[] - Null:
null
JavaScript expressions and functions are not allowed.
属性值必须为以下类型之一:
- 布尔值:或
truefalse - 数字:整数或浮点数
- 字符串:双引号包裹的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 , , or may have semantic meaning and should be kept.
0false""json
{
"volume": 10,
"balance": 0,
"currentlyPlaying": null
}Better:
json
{
"volume": 10,
"balance": 0
}除非有强烈的语义需求,否则应移除值为空或null的属性。值为、或的属性可能具备语义意义,应予以保留。
0false""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:
- - Version of the API (string)
apiVersion - - Client-set value echoed by server (string)
context - - Server-assigned response identifier (string)
id - - Operation performed (string)
method - - Input parameters for RPC requests (object)
params - - Container for successful response data (object)
data - - Error details if request failed (object)
error
A response should contain either or , but not both.
dataerrorjson
{
"apiVersion": "2.1",
"data": {
"kind": "user",
"id": "12345",
"name": "John Doe"
}
}JSON响应可包含以下可选顶层属性:
- - API版本(字符串)
apiVersion - - 客户端设置、服务器回显的值(字符串)
context - - 服务器分配的响应标识符(字符串)
id - - 执行的操作(字符串)
method - - RPC请求的输入参数(对象)
params - - 成功响应数据的容器(对象)
data - - 请求失败时的错误详情(对象)
error
响应中应仅包含或中的一个,不可同时存在。
dataerrorjson
{
"apiVersion": "2.1",
"data": {
"kind": "user",
"id": "12345",
"name": "John Doe"
}
}Data Object Properties
数据对象属性
Common properties in the object:
data- - Type of object (should be first property)
kind - - Fields present in partial response
fields - - Entity tag for versioning
etag - - Unique identifier
id - - Language code (BCP 47)
lang - - Last update timestamp (RFC 3339)
updated - - Boolean marker for deleted entries
deleted - - Array of items (should be last property)
items
data- - 对象类型(应作为第一个属性)
kind - - 部分响应中包含的字段
fields - - 用于版本控制的实体标签
etag - - 唯一标识符
id - - 语言代码(BCP 47)
lang - - 最后更新时间戳(RFC 3339)
updated - - 标记条目是否已删除的布尔值
deleted - - 项目数组(应作为最后一个属性)
items
Pagination Properties
分页属性
For paginated data in the object:
data- - Number of items in current response
currentItemCount - - Requested page size
itemsPerPage - - Index of first item (1-based)
startIndex - - Total available items
totalItems - - Current page number (1-based)
pageIndex - - Total number of pages
totalPages - - URI template for pagination
pagingLinkTemplate
data- - 当前响应中的项目数量
currentItemCount - - 请求的页面大小
itemsPerPage - - 第一个项目的索引(从1开始)
startIndex - - 可用项目总数
totalItems - - 当前页码(从1开始)
pageIndex - - 总页数
totalPages - - 分页用的URI模板
pagingLinkTemplate
Link Properties
链接属性
Link properties in the object:
data- /
self- Link to retrieve this resourceselfLink - /
edit- Link to update/delete this resourceeditLink - /
next- Link to next pagenextLink - /
previous- Link to previous pagepreviousLink
data- /
self- 获取此资源的链接selfLink - /
edit- 更新/删除此资源的链接editLink - /
next- 下一页的链接nextLink - /
previous- 上一页的链接previousLink
Error Object Properties
错误对象属性
When an error occurs, use the object:
error- - HTTP status code (integer)
code - - Human-readable error message (string)
message - - Array of error details (array)
errors
Each error in array can have:
errors- - Service identifier
domain - - Error type identifier
reason - - Detailed error message
message - - Where error occurred
location - - How to interpret location
locationType - - URI to help documentation
extendedHelp - - URI to error report form
sendReport
json
{
"apiVersion": "2.0",
"error": {
"code": 404,
"message": "File Not Found",
"errors": [{
"domain": "Calendar",
"reason": "ResourceNotFoundException",
"message": "File Not Found"
}]
}
}发生错误时,使用对象:
error- - HTTP状态码(整数)
code - - 易读的错误信息(字符串)
message - - 错误详情数组(数组)
errors
errors- - 服务标识符
domain - - 错误类型标识符
reason - - 详细错误信息
message - - 错误发生位置
location - - 位置的解释方式
locationType - - 帮助文档的URI
extendedHelp - - 错误报告表单的URI
sendReport
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:
- should be first - Helps parsers determine object type early
kind - should be last in
items- Allows reading collection metadata before parsing itemsdata
json
{
"data": {
"kind": "album",
"title": "My Photo Album",
"totalItems": 100,
"items": [
{
"kind": "photo",
"title": "My First Photo"
}
]
}
}虽然JSON不强制要求属性顺序,但特定顺序可提升解析效率:
- 应置于首位 - 帮助解析器尽早确定对象类型
kind - 应置于
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 in responses
apiVersion - Use for success,
datafor failures (not both)error - Place first in objects
kind - Place last in
itemsobjectdata - Use reserved property names for standard semantics
- 响应中包含
apiVersion - 成功响应使用,失败响应使用
data(不可同时使用)error - 置于对象首位
kind - 置于
items对象末尾data - 为标准语义使用保留属性名称
Additional Resources
额外资源
Reference Files
参考文件
For detailed specifications:
- - Complete naming rules and reserved keywords
references/naming-conventions.md - - Full list of reserved property names and their semantics
references/reserved-properties.md - - Detailed pagination implementation patterns
references/pagination-patterns.md
如需详细规范,请查看:
- - 完整的命名规则与保留关键字
references/naming-conventions.md - - 保留属性名称及其语义的完整列表
references/reserved-properties.md - - 详细的分页实现模式
references/pagination-patterns.md
Example Files
示例文件
Working examples in :
examples/- - Standard API response structure
examples/api-response.json - - Error handling example
examples/error-response.json - - Pagination example with all properties
examples/paginated-response.json
examples/- - 标准API响应结构
examples/api-response.json - - 错误处理示例
examples/error-response.json - - 包含所有属性的分页示例
examples/paginated-response.json