天天看點

JSON風格指南-真經

版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/chinahuyong/article/details/46513911

簡介

JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式。它基于ECMAScript的一個子集。 JSON采用完全獨立于語言的文本格式,但是也使用了類似于C語言家族的習慣(包括C、C++、C#、Java、JavaScript、Perl、Python等)。這些特性使JSON成為理想的資料交換語言。 易于人閱讀和編寫,同時也易于機器解析和生成(網絡傳輸速率)。

該風格指南是對在Google建立JSON APIs而提供的指導性準則和建議。總體來講,JSON APIs應遵循JSON.org上的規範。這份風格指南澄清和标準化了特定情況,進而使Google的JSON APIs有一種标準的外觀和感覺。這些指南适用于基于RPC和基于REST風格的API的JSON請求和響應。

本文譯自:

http://google-styleguide.googlecode.com/svn/trunk/jsoncstyleguide.xml
JSON風格指南-真經

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E5%AE%9A%E4%B9%89 定義

為了更好地實作這份風格指南的目的,下面幾項需要說明:

  • 屬性(property) - JSON對象内的鍵值對(name/value pair)
  • 屬性名(property name) - 屬性的名稱(或鍵)
  • 屬性值(property value) - 配置設定給屬性的值

示例:

{

// 一組鍵值對稱作一個 "屬性".

"propertyName": "propertyValue"

}

Javascript的數字(number)包含所有的浮點數,這是一個寬泛的指定。在這份指南中,數字(number)指代Javascript中的數字(number)類型,而整型(integer)則指代整型。

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E4%B8%80%E8%88%AC%E5%87%86%E5%88%99 一般準則

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E6%B3%A8%E9%87%8A 注釋

JSON對象中不包含注釋。

JSON對象中不應該包含注釋。該指南中的某些示例含有注釋。但這僅僅是為了說明示例。

{

// 你可能在下面的示例中看到注釋,

// 但不要在你的JSON資料中加入注釋.

"propertyName": "propertyValue"

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E5%8F%8C%E5%BC%95%E5%8F%B7 雙引号

使用雙引号

如果(某個)屬性需要引号,則必須使用雙引号。所有的屬性名必須在雙引号内。字元類型的屬性值必須使用雙引号。其它類型值(如布爾或數字)不應該使用雙引号。

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E6%89%81%E5%B9%B3%E5%8C%96%E6%95%B0%E6%8D%AE-vs-%E7%BB%93%E6%9E%84%E5%B1%82%E6%AC%A1 扁平化資料 VS 結構層次

不能為了友善而将資料任意分組

JSON中的資料元素應以扁平化方式呈現。不能為了友善而将資料任意分組。

在某些情況下,比如描述單一結構的一批屬性,因為它被用來保持結構層次,因而是有意義的。但是遇到這些情況還是應當慎重考慮,記住隻有語義上有意義的時候才使用它。例如,一個位址可以有表示兩種方式,但結構化的方式對開發人員來講可能更有意義:

扁平化位址:

{

"company": "Google",

"website": "

http://www.google.com/

",

"addressLine1": "111 8th Ave",

"addressLine2": "4th Floor",

"state": "NY",

"city": "New York",

"zip": "10011"

}

結構化位址:

{

"company": "Google",

"website": "

http://www.google.com/

",

"address": {

"line1": "111 8th Ave",

"line2": "4th Floor",

"state": "NY",

"city": "New York",

"zip": "10011"

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E5%B1%9E%E6%80%A7%E5%90%8D%E5%87%86%E5%88%99 屬性名準則

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E5%B1%9E%E6%80%A7%E5%90%8D%E6%A0%BC%E5%BC%8F 屬性名格式

選擇有意義的屬性名

屬性名必須遵循以下準則:

  • 屬性名應該是具有定義語義的有意義的名稱。
  • 屬性名必須是駝峰式的,ASCII碼字元串。
  • 首字元必須式字母,下劃線(_)或美元符号($)。
  • 随後的其他字元可以是字母,數字,下劃線(_)或美元符号($)。
  • 應該避免使用Javascript中的保留關鍵字(下文附有Javascript保留字清單)

這些準則反映JavaScript辨別符命名的指導方針。使JavaScript的用戶端可以使用點符号來通路屬性。(例如,

result.thisIsAnInstanceVariable

).

下面是一個對象的一個屬性的例子:

{

"thisPropertyIsAnIdentifier": "identifier value"

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#json-map%E4%B8%AD%E7%9A%84%E9%94%AE%E5%90%8D JSON Map中的鍵名

在JSON Map中鍵名可以使用任意Unicode字元

當JSON對象作為Map(映射)使用時,屬性的名稱命名規則并不适用。Map(也稱作關聯數組)是一個具有任意鍵/值對的資料類型,這些鍵/值對通過特定的鍵來通路相應的值。JSON對象和JSON Map在運作時看起來是一樣的;這個特性與API設計相關。當JSON對象被當作map使用時,API檔案應當做出說明。

Map的鍵名不一定要遵循屬性名稱的命名準則。鍵名可以包含任意的Unicode字元。用戶端可使用maps熟悉的方括号來通路這些屬性。(例如

result.thumbnails["72"]

{

// "address" 屬性是一個子對象

// 包含位址的各部分.

"address": {

"addressLine1": "123 Anystreet",

"city": "Anytown",

"state": "XX",

"zip": "00000"

},

// "address" 是一個映射

// 含有響應規格所對應的URL,用來映射thumbnail url的像素規格

"thumbnails": {

"72": "

http://url.to.72px.thumbnail

",

"144": "

http://url.to.144px.thumbnail

"

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E4%BF%9D%E7%95%99%E7%9A%84%E5%B1%9E%E6%80%A7%E5%90%8D%E7%A7%B0 保留的屬性名稱

某些屬性名稱會被保留以便能在多個服務間相容使用

保留屬性名稱的詳細資訊,連同完整的清單,可在本指南後面的内容中找到。服務應按照被定義的語義來使用屬性名稱。

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E5%8D%95%E6%95%B0%E5%B1%9E%E6%80%A7%E5%90%8D-vs-%E5%A4%8D%E6%95%B0%E5%B1%9E%E6%80%A7%E5%90%8D 單數屬性名 VS 複數屬性名

數組類型應該是複數屬性名。其它屬性名都應該是單數。

數組通常包含多個條目,複數屬性名就反映了這點。在下面這個保留名稱中可以看到例子。屬性名items是複數因為它描述的是一組對象。大多數的其它字段是單數。

當然也有例外,尤其是涉及到數字的屬性值的時候。例如,在保留屬性名中,totalItems 比 totalItem更合理。然後,從技術上講,這并不違反風格指南,因為 totalItems 可以被看作 totalOfItems, 其中 total 是單數(依照風格指南),OfItems 用來限定總數。字段名也可被改為 itemCount,這樣看起來更象單數.

{

// 單數

"author": "lisa",

// 一組同胞, 複數

"siblings": [ "bart", "maggie"],

// "totalItem" 看起來并不對

"totalItems": 10,

// 但 "itemCount" 要好些

"itemCount": 10,

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E5%91%BD%E5%90%8D%E5%86%B2%E7%AA%81 命名沖突

通過選擇新的屬性名或将API版本化來避免命名沖突

新的屬性可在将來被添加進保留清單中。JSON中不存在命名空間。如果存在命名沖突,可通過選擇新的屬性名或者版本化來解決這個問題。例如,假設我們由下面的JSON對象開始:

{

"apiVersion": "1.0",

"data": {

"recipeName": "pizza",

"ingredients": ["tomatoes", "cheese", "sausage"]

}

}

如果我們希望将來把ingredients列為保留字,我們可以通過下面兩件事情來達成。 1.選一個不同的名字

{

"apiVersion": "1.0",

"data": {

"recipeName": "pizza",

"ingredientsData": "Some new property",

"ingredients": ["tomatoes", "cheese", "sausage"]

}

}

2.在主版本上重新命名屬性

{

"apiVersion": "2.0",

"data": {

"recipeName": "pizza",

"ingredients": "Some new property",

"recipeIngredients": ["tomatos", "cheese", "sausage"]

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E5%B1%9E%E6%80%A7%E5%80%BC%E5%87%86%E5%88%99 屬性值準則

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E5%B1%9E%E6%80%A7%E5%80%BC%E6%A0%BC%E5%BC%8F 屬性值格式

屬性值必須是Unicode 的 booleans(布爾), 數字(numbers), 字元串(strings), 對象(objects), 數組(arrays), 或 null.

JSON.org上的标準準确的說明了哪些類型的資料可以作為屬性值。這包含Unicode的布爾(booleans), 數字(numbers), 字元串(strings), 對象(objects), 數組(arrays), 或 null。JavaScript表達式是不被接受的。APIs應該支援該準則,并為某個特定的屬性選擇最合适的資料類型(比如,用numbers代表numbers等)。

好的例子:

{

"canPigsFly": null,     // null

"areWeThereYet": false, // boolean

"answerToLife": 42,     // number

"name": "Bart",         // string

"moreData": {},         // object

"things": []            // array

}

不好的例子:

{

"aVariableName": aVariableName,         // Bad - JavaScript 辨別符

"functionFoo": function() { return 1; } // Bad - JavaScript 函數

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E7%A9%BA%E6%88%96null-%E5%B1%9E%E6%80%A7%E5%80%BC 空或Null 屬性值

考慮移除空或null值

如果一個屬性是可選的或者包含空值或null值,考慮從JSON中去掉該屬性,除非它的存在有很強的語義原因。

{

"volume": 10,

// 即使 "balance" 屬性值是零, 它也應當被保留,

// 因為 "0" 表示 "均衡"

// "-1" 表示左傾斜和"+1" 表示右傾斜

"balance": 0,

// "currentlyPlaying" 是null的時候可被移除

// "currentlyPlaying": null

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E6%9E%9A%E4%B8%BE%E5%80%BC 枚舉值

枚舉值應當以字元串的形式呈現

随着APIs的發展,枚舉值可能被添加,移除或者改變。将枚舉值當作字元串可以使下遊使用者幽雅的處理枚舉值的變更。

Java代碼:

public

enum

Color {

WHITE,

BLACK,

RED,

YELLOW,

BLUE

}

JSON對象:

{

"color": "WHITE"

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E5%B1%9E%E6%80%A7%E5%80%BC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B 屬性值資料類型

上面提到,屬性值必須是布爾(booleans), 數字(numbers), 字元串(strings), 對象(objects), 數組(arrays), 或 null. 然而在處理某些值時,定義一組标準的資料類型是非常有用的。這些資料類型必須始終是字元串,但是為了便于解析,它們也會以特定的方式被格式化。

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E6%97%A5%E6%9C%9F%E5%B1%9E%E6%80%A7%E5%80%BC 日期屬性值

日期應該使用RFC3339建議的格式

日期應該是RFC 3339所建議的字元串格式。

{

"lastUpdate": "2007-11-06T16:34:41.000Z"

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E6%97%B6%E9%97%B4%E9%97%B4%E9%9A%94%E5%B1%9E%E6%80%A7%E5%80%BC 時間間隔屬性值

時間間隔應該使用ISO 8601建議的格式

時間間隔應該是ISO 8601所建議的字元串格式。

{

// 三年, 6個月, 4天, 12小時,

// 三十分鐘, 5秒

"duration": "P3Y6M4DT12H30M5S"

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E7%BA%AC%E5%BA%A6%E7%BB%8F%E5%BA%A6%E5%B1%9E%E6%80%A7%E5%80%BC 緯度/經度屬性值

緯度/經度應該使用ISO 6709建議的格式

緯度/經度應該是ISO 6709所建議的字元串格式。 而且, 它應該更偏好使用 e ±DD.DDDD±DDD.DDDD 角度格式.

{

// 自由女神像的緯度/經度位置.

"statueOfLiberty": "+40.6894-074.0447"

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#json%E7%BB%93%E6%9E%84%E5%92%8C%E4%BF%9D%E7%95%99%E5%B1%9E%E6%80%A7%E5%90%8D JSON結構和保留屬性名

為了使APIs保持一緻的借口,JSON對象應當使用以下的結構。該結構适用于JSON的請求和響應。在這個結構中,某些屬性名将被保留用作特殊用途。這些屬性并不是必需的,也就是說,每個保留的屬性可能出現零次或一次。但是如果服務需要這些屬性,建議遵循該命名條約。下面是一份JSON結構語義表,以Orderly格式呈現(現在已經被納入 JSONSchema)。你可以在該指南的最後找到關于JSON結構的例子。

object {

string apiVersion?;

string context?;

string id?;

string method?;

object {

string id?

}* params?;

object {

string kind?;

string fields?;

string etag?;

string id?;

string lang?;

string updated?; # date formatted RFC 3339

boolean deleted?;

integer currentItemCount?;

integer itemsPerPage?;

integer startIndex?;

integer totalItems?;

integer pageIndex?;

integer totalPages?;

string pageLinkTemplate /^https?:/ ?;

object {}* next?;

string nextLink?;

object {}* previous?;

string previousLink?;

object {}* self?;

string selfLink?;

object {}* edit?;

string editLink?;

array [

object {}*;

] items?;

}* data?;

object {

integer code?;

string message?;

array [

object {

string domain?;

string reason?;

string message?;

string location?;

string locationType?;

string extendedHelp?;

string sendReport?;

}*;

] errors?;

}* error?;

}*;

JSON對象有一些頂級屬性,然後是data對象或error對象,這兩者不會同時出現。下面是這些屬性的解釋。

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E9%A1%B6%E7%BA%A7%E4%BF%9D%E7%95%99%E5%B1%9E%E6%80%A7%E5%90%8D%E7%A7%B0 頂級保留屬性名稱

頂級的JSON對象可能包含下面這些屬性

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#apiversion apiVersion

屬性值類型: 字元串(string)
父節點: -
           

呈現請求中服務API期望的版本,以及在響應中儲存的服務API版本。應随時提供apiVersion。這與資料的版本無關。将資料版本化應該通過其他的機制來處理,如etag。

{ "apiVersion": "2.1" }
           

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#context context

屬性值類型: 字元串(string)
父節點: -
           

用戶端設定這個值,伺服器通過資料作出回應。這在JSON-P和批進行中很有用,使用者可以使用context将響應與請求關聯起來。該屬性是頂級屬性,因為不管響應是成功還是有錯誤,context總應當被呈現出來。context不同于id在于context由使用者提供而id由服務配置設定。

請求 #1:

http://www.google.com/myapi?context=bart
           

請求 #2:

http://www.google.com/myapi?context=lisa
           

響應 #1:

{
  "context": "bart",
  "data": {
    "items": []
  }
}
           

響應 #2:

{
  "context": "lisa",
  "data": {
    "items": []
  }
}
           

公共的JavaScript處理器通過編碼同時處理以下兩個響應:

function handleResponse(response) {
  if (response.result.context == "bart") {
    // 更新頁面中的 "Bart" 部分。
  } else if (response.result.context == "lisa") {
    // 更新頁面中的 "Lisa" 部分。
  }
}
           

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#id id

屬性值類型: 字元串(string)
父節點: -
           

服務提供用于識别響應的辨別(無論請求是成功還是有錯誤)。這對于将服務日志和單獨收到的響應對應起來很有用。

{ "id": "1" }
           

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#method method

屬性值類型: 字元串(string)
父節點: -
           

表示對資料即将執行,或已被執行的操作。在JSON請求的情況下,method屬性可以用來指明對資料進行何種操作。在JSON響應的情況下,method屬性表明對資料進行了何種操作。

一個JSON-RPC請求的例子,其中method屬性表示要在params上執行的操作:

{
  "method": "people.get",
  "params": {
    "userId": "@me",
    "groupId": "@self"
  }
}
           

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#params params

屬性值類型: 對象(object)
父節點: -
           

這個對象作為輸入參數的映射發送給RPC請求。它可以和method屬性一起用來執行RPC功能。若RPC方法不需要參數,則可以省略該屬性。

{
  "method": "people.get",
  "params": {
    "userId": "@me",
    "groupId": "@self"
  }
}
           

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#data data

屬性值類型: 對象(object)
父節點: -
           

包含響應的所有資料。該屬性本身擁有許多保留屬性名,下面會有相應的說明。服務可以自由地将自己的資料添加到這個對象。一個JSON響應要麼應當包含一個data對象,要麼應當包含error對象,但不能兩者都包含。如果data和error同時出現,則error對象優先。

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#error error

屬性值類型: 對象(object)
父節點: -
           

表明錯誤發生,提供錯誤的詳細資訊。錯誤的格式支援從服務傳回一個或多個錯誤。一個JSON響應可以有一個data對象或者一個error對象,但不能兩者都包含。如果data和error都出現,error對象優先。

{

"apiVersion": "2.0",

"error": {

"code": 404,

"message": "File Not Found",

"errors": [{

"domain": "Calendar",

"reason": "ResourceNotFoundException",

"message": "File Not Found

}]

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#data%E5%AF%B9%E8%B1%A1%E7%9A%84%E4%BF%9D%E7%95%99%E5%B1%9E%E6%80%A7%E5%90%8D data對象的保留屬性名

JSON對象的data屬性可能包含以下屬性。

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#datakind data.kind

屬性值類型: 字元串(sting)
父節點: data
           

kind屬性是對某個特定的對象存儲何種類型的資訊的指南。可以把它放在data層次,或items的層次,或其它任何有助于區分各類對象的對象中。如果kind對象被提供,它應該是對象的第一個屬性(詳見下面的屬性順序部分)。

// "Kind" indicates an "album" in the Picasa API.

{"data": {"kind": "album"}}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#datafields data.fields

屬性值類型: 字元串(string)
父節點: data
           

表示做了部分GET之後響應中出現的字段,或做了部分PATCH之後出現在請求中的字段。該屬性僅在做了部分GET請求/批處理時存在,且不能為空。

{

"data": {

"kind": "user",

"fields": "author,id",

"id": "bart",

"author": "Bart"

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#dataetag data.etag

屬性值類型: 字元串(string)
父節點: data
           

響應時提供etag。關于GData APIs中的ETags詳情可以在這裡找到:

http://code.google.com/apis/gdata/docs/2.0/reference.html#ResourceVersioning

{"data": {"etag": "W/"C0QBRXcycSp7ImA9WxRVFUk.""}}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#dataid data.id

屬性值類型: 字元串(string)
父節點: data
           

一個全局唯一辨別符用于引用該對象。id屬性的具體細節都留給了服務。

{"data": {"id": "12345"}}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#datalang data.lang

屬性值類型: 字元串(string)(格式由BCP 47指定)
父節點: data (或任何子元素)
           

表示該對象内其他屬性的語言。該屬性模拟HTML的lang屬性和XML的xml:lang屬性。值應該時BCP 47中定義的一種語言值。如果一個單一的JSON對象包含的資料有多種語言,服務負責制定和标明的lang屬性的适當位置。

{"data": {

"items": [

{ "lang": "en",

"title": "Hello world!" },

{ "lang": "fr",

"title": "Bonjour monde!" }

]}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#dataupdated data.updated

屬性值類型: 字元串(string)(格式由RFC 3339指定)
父節點: data
           

指明條目更新的最後日期/時間(RFC 3339),由服務規定。

{"data": {"updated": "2007-11-06T16:34:41.000Z"}}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#datadeleted data.deleted

屬性值類型: 布爾(boolean)
父節點: data (或任何子元素)
           

一個标記元素,當出現時,表示包含的條目已被删除。如果提供了删除屬性,它的值必須為true;為false會導緻混亂,應該避免。

{"data": {

"items": [

{ "title": "A deleted entry",

"deleted": true

}

]}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#dataitems data.items

屬性值類型: 數組(array)
父節點: data
           

屬性名items被保留用作表示一組條目(例如,Picasa中的圖檔,YouTube中的視訊)。這種結構的目的是給與目前結果相關的集合提供一個标準位置。例如,知道頁面上的items是數組,JSON輸出便可能插入一個通用的分頁系統。如果items存在,它應該是data對象的最後一個屬性。(詳見下面的屬性順序部分)。

{

"data": {

"items": [

{ /* Object #1 */ },

{ /* Object #2 */ },

...

]

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E7%94%A8%E4%BA%8E%E5%88%86%E9%A1%B5%E7%9A%84%E4%BF%9D%E7%95%99%E5%B1%9E%E6%80%A7%E5%90%8D 用于分頁的保留屬性名

下面的屬性位于data對象中,用來給一列資料分頁。一些語言和概念是從OpenSearch規範中借鑒過來的。

下面的分頁資料允許各種風格的分頁,包括:

  • 上一頁/下一頁 - 允許使用者在清單中前進和後退,一次一頁。nextLink 和previousLink屬性 (下面的"連結保留屬性名"部分有描述) 用于這種風格的分頁。
  • 基于索引的分頁 - 允許使用者直接跳到條目清單的某個條目位置。例如,要從第200個條目開始載入10個新的條目,開發者可以給使用者提供一個URL的查詢字元串?startIndex=200。
  • 基于頁面的分頁 - 允許使用者直接跳到條目内的具體頁。這跟基于索引的分頁很類似,但節省了開發者額外的步驟,不需再為新一頁的條目計算條目索引。例如,開發人員可以直接跳到第20頁,而不是跳到第200條條目。基于頁面分頁的網址,可以使用查詢字元串?page=1或?page=20。pageIndex和 totalPages 屬性用作這種風格的分頁.

在這份指南的最後可以找到如何使用這些屬性來實作分頁的例子。

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#datacurrentitemcount data.currentItemCount

屬性值類型: 整數(integer)
父節點: data
           

結果集中的條目數目。應該與items.length相等,并作為一個便利屬性提供。例如,假設開發者請求一組搜尋條目,并且要求每頁10條。查詢集共有14條。第一個條目頁将會有10個條目,是以itemsPerPage和currentItemCount都應該等于10。下一頁的條目還剩下4條;itemsPerPage仍然是10,但是currentItemCount是4.

{

"data": {

// "itemsPerPage" 不需要與 "currentItemCount" 比對

"itemsPerPage": 10,

"currentItemCount": 4

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#dataitemsperpage data.itemsPerPage

屬性值類型: 整數(integer)
父節點: data
           

items結果的數目。未必是data.items數組的大小;如果我們檢視的是最後一頁,data.items的大小可能小于itemsPerPage。但是,data.items的大小不應超過itemsPerPage。

{

"data": {

"itemsPerPage": 10

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#datastartindex data.startIndex

屬性值類型: 整數(integer)
父節點: data
           

data.items中第一個條目的索引。為了一緻,startIndex應從1開始。例如,第一組items中第一條的startIndex應該是1。如果使用者請求下一組資料,startIndex可能是10。

{

"data": {

"startIndex": 1

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#datatotalitemsx data.totalItemsx

屬性值類型: 整數(integer)
父節點: data
           

目前集合中可用的總條目數。例如,如果使用者有100篇部落格文章,響應可能隻包含10篇,但是totalItems應該是100。

{

"data": {

"totalItems": 100

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#datapaginglinktemplate data.pagingLinkTemplate

屬性值類型: 字元串(string)
父節點: data
           

URL模闆指出使用者可以如何計算随後的分頁連結。URL模闆中也包含一些保留變量名:表示要載入的條目的{index},和要載入的頁面的{pageIndex}。

{

"data": {

"pagingLinkTemplate": "

http://www.google.com/search/hl=en&q=chicago

+style+pizza&start={index}&sa=N"

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#datapageindex data.pageIndex

屬性值類型: 整數(integer)
父節點: data
           

條目的目前頁索引。為了一緻,pageIndex應從1開始。例如,第一頁的pageIndex是1。pageIndex也可以通過基于條目的分頁而計算出來pageIndex = floor(startIndex / itemsPerPage) + 1。

{

"data": {

"pageIndex": 1

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#datatotalpages data.totalPages

屬性值類型: 整數(integer)
父節點: data
           

目前結果集中的總頁數。totalPages也可以通過上面基于條目的分頁屬性計算出來: totalPages = ceiling(totalItems / itemsPerPage).。

{

"data": {

"totalPages": 50

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E7%94%A8%E4%BA%8E%E9%93%BE%E6%8E%A5%E7%9A%84%E4%BF%9D%E7%95%99%E5%B1%9E%E6%80%A7%E5%90%8D 用于連結的保留屬性名

下面的屬性位于data對象中,用來表示對其他資源的引用。有兩種形式的連結屬性:1)對象,它可以包含任何種類的引用(比如JSON-RPC對象),2)URL字元串,表示資源的URIs(字尾總為'Link')。

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#dataself--dataselflink data.self / data.selfLink

屬性值類型: 對象(object)/字元串(string)
父節點: data
           

自身連結可以用于取回條目資料。比如,在使用者的Picasa相冊中,條目中的每個相冊對象都會包含一個selfLink用于檢索這個相冊的相關資料。

{

"data": {

"self": { },

"selfLink": "

http://www.google.com/feeds/album/1234

"

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#dataedit--dataeditlink data.edit / data.editLink

屬性值類型: 對象(object)/字元串(string)
父節點: data
           

編輯連結表明使用者可以發送更新或删除請求。這對于REST風格的APIs很有用。該連結僅在使用者能夠更新和删除該條目時提供。

{

"data": {

"edit": { },

"editLink": "

http://www.google.com/feeds/album/1234/edit

"

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#datanext--datanextlink data.next / data.nextLink

屬性值類型: 對象(object)/字元串(string)
父節點: data
           

該下一頁連結标明如何取得更多資料。它指明載入下一組資料的位置。它可以同itemsPerPage,startIndex 和 totalItems屬性一起使用用于分頁資料。

{

"data": {

"next": { },

"nextLink": "

http://www.google.com/feeds/album/1234/next

"

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#dataprevious--datapreviouslink data.previous / data.previousLink

屬性值類型: 對象(object)/字元串(string)
父節點: data
           

該上一頁連結标明如何取得更多資料。它指明載入上一組資料的位置。它可以連同itemsPerPage,startIndex 和 totalItems屬性用于分頁資料。

{

"data": {

"previous": { },

"previousLink": "

http://www.google.com/feeds/album/1234/next

"

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E9%94%99%E8%AF%AF%E5%AF%B9%E8%B1%A1%E4%B8%AD%E7%9A%84%E4%BF%9D%E7%95%99%E5%B1%9E%E6%80%A7%E5%90%8D 錯誤對象中的保留屬性名

JSON對象的error屬性應包含以下屬性。

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#errorcode error.code

屬性值類型: 整數(integer)
父節點: error
           

表示該錯誤的編号。這個屬性通常表示HTTP響應碼。如果存在多個錯誤,code應為第一個出錯的錯誤碼。

{

"error":{

"code": 404

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#errormessage error.message

屬性值類型: 字元串(string)
父節點: error
           

一個人類可讀的資訊,提供有關錯誤的詳細資訊。如果存在多個錯誤,message應為第一個錯誤的錯誤資訊。

{

"error":{

"message": "File Not Found"

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#errorerrors error.errors

屬性值類型: 數組(array)
父節點: error
           

包含關于錯誤的附加資訊。如果服務傳回多個錯誤。errors數組中的每個元素表示一個不同的錯誤。

{ "error": { "errors": [] } }   
           

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#errorerrorsdomain error.errors[].domain

屬性值類型: 字元串(string)
父節點: error.errors
           

服務抛出該錯誤的唯一識别符。它幫助區分服務的從普通協定錯誤(如,找不到檔案)中區分出具體錯誤(例如,給月曆插入事件的錯誤)。

{

"error":{

"errors": [{"domain": "Calendar"}]

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#errorerrorsreason error.errors[].reason

屬性值類型: 字元串(string)
父節點: error.errors
           

該錯誤的唯一識别符。不同于error.code屬性,它不是HTTP響應碼。

{

"error":{

"errors": [{"reason": "ResourceNotFoundException"}]

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#errorerrorsmessage error.errors[].message

屬性值類型: 字元串(string)
父節點: error.errors
           

一個人類可讀的資訊,提供有關錯誤的更多細節。如果隻有一個錯誤,該字段應該與error.message比對。

{

"error":{

"code": 404

"message": "File Not Found",

"errors": [{"message": "File Not Found"}]

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#errorerrorslocation error.errors[].location

屬性值類型: 字元串(string)
父節點: error.errors
           

錯誤發生的位置(根據locationType字段解釋該值)。

{

"error":{

"errors": [{"location": ""}]

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#errorerrorslocationtype error.errors[].locationType

屬性值類型: 字元串(string)
父節點: error.errors
           

标明如何解釋location屬性。

{

"error":{

"errors": [{"locationType": ""}]

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#errorerrorsextendedhelp error.errors[].extendedHelp

屬性值類型: 字元串(string)
父節點: error.errors
           

help text的URI,使錯誤更易于了解。

示例:(注:原示例這裡有筆誤,中文版這裡做了校正)

{
  "error":{
    "errors": [{"extendedHelp": "http://url.to.more.details.example.com/"}]
  }
}
           

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#errorerrorssendreport error.errors[].sendReport

屬性值類型: 字元串(string)
父節點: error.errors
           

report form的URI,服務用它來收集錯誤狀态的資料。該URL會預先載入描述請求的參數

{

"error":{

"errors": [{"sendReport": "

http://report.example.com/

"}]

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E5%B1%9E%E6%80%A7%E9%A1%BA%E5%BA%8F 屬性順序

在JSON對象中屬性可有任意順序。然而,在某些情況下,有序的屬性可以幫助分析器快速解釋資料,并帶來更好的性能。在移動環境下的解析器就是個例子,在這種情況下,性能和記憶體是至關重要的,不必要的解析也應盡量避免。

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#kind%E5%B1%9E%E6%80%A7 Kind屬性

Kind屬性應為第一屬性

假設一個解析器負責将一個原始JSON流解析成一個特定的對象。kind屬性會引導解析器将适合的對象執行個體化。因而它應該是JSON對象的第一個屬性。這僅适用于對象有一個kind屬性的情況(通常可以在data和items屬性中找到)。

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#items%E5%B1%9E%E6%80%A7 Items屬性

items應該是data對象的最後一個屬性

這使得閱讀每一個具體條目前前已讀所有的集合屬性。在有很多條目的情況下,這樣就避免了開發人員隻需要從資料的字段時不必要的解析這些條目。

這讓閱讀所有集合屬性先于閱讀單個條目。如遇多個條目的情況,當開發者僅需要資料中的字段時,這就可避免解析不必要的條目。

屬性順序示例:

// "kind" 屬性區分 "album" 和 "photo".

// "Kind" 始終是它父對象的第一個屬性.

// "items" 屬性是 "data" 對象的最後一個屬性.

{

"data": {

"kind": "album",

"title": "My Photo Album",

"description": "An album in the user's account",

"items": [

{

"kind": "photo",

"title": "My First Photo"

}

]

}

}

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E7%A4%BA%E4%BE%8B 示例

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#youtube-json-api YouTube JSON API

這是YouTube JSON API響應對象的示例。你可以從中學到更多關于YouTube JSON API的内容:

http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html

{

"apiVersion": "2.0",

"data": {

"updated": "2010-02-04T19:29:54.001Z",

"totalItems": 6741,

"startIndex": 1,

"itemsPerPage": 1,

"items": [

{

"id": "BGODurRfVv4",

"uploaded": "2009-11-17T20:10:06.000Z",

"updated": "2010-02-04T06:25:57.000Z",

"uploader": "docchat",

"category": "Animals",

"title": "From service dog to SURFice dog",

"description": "Surf dog Ricochets inspirational video ...",

"tags": [

"Surf dog",

"dog surfing",

"dog",

"golden retriever",

],

"thumbnail": {

"default": "

http://i.ytimg.com/vi/BGODurRfVv4/default.jpg

",

"hqDefault": "

http://i.ytimg.com/vi/BGODurRfVv4/hqdefault.jpg

"

},

"player": {

"default": "

http://www.youtube.com/watch?v=BGODurRfVv4&feature=youtube_gdata

",

"mobile": "

http://m.youtube.com/details?v=BGODurRfVv4

"

},

"content": {

"1": "

rtsp://v5.cache6.c.youtube.com/CiILENy73wIaGQn-Vl-0uoNjBBMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp

",

"5": "

http://www.youtube.com/v/BGODurRfVv4?f=videos&app=youtube_gdata

",

"6": "

rtsp://v7.cache7.c.youtube.com/CiILENy73wIaGQn-Vl-0uoNjBBMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp

"

},

"duration": 315,

"rating": 4.96,

"ratingCount": 2043,

"viewCount": 1781691,

"favoriteCount": 3363,

"commentCount": 1007,

"commentsAllowed": true

}

]

}

}

  

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E5%88%86%E9%A1%B5%E7%A4%BA%E4%BE%8B 分頁示例

如何将Google搜尋條目作為JSON對象展現出來,對分頁變量也有特别關注。

這個示例僅用作說明。下面的API實際上并不存在。

這是Google搜尋結果頁面的示例: 

https://camo.githubusercontent.com/c8ff0de46d7cb966ddae8b3350960400fdd6962d/687474703a2f2f676f6f676c652d7374796c6567756964652e676f6f676c65636f64652e636f6d2f73766e2f7472756e6b2f6a736f6e637374796c6567756964655f6578616d706c655f30312e706e67 https://camo.githubusercontent.com/0341a3abf1faaffd6dc67039efd964336d285f54/687474703a2f2f676f6f676c652d7374796c6567756964652e676f6f676c65636f64652e636f6d2f73766e2f7472756e6b2f6a736f6e637374796c6567756964655f6578616d706c655f30322e706e67

這是該頁面JSON形式的呈現:

{

"apiVersion": "2.1",

"id": "1",

"data": {

"query": "chicago style pizza",

"time": "0.1",

"currentItemCount": 10,

"itemsPerPage": 10,

"startIndex": 11,

"totalItems": 2700000,

"nextLink": "

http://www.google.com/search?hl=en&q=chicago

+style+pizza&start=20&sa=N"

"previousLink": "

http://www.google.com/search?hl=en&q=chicago

+style+pizza&start=0&sa=N",

"pagingLinkTemplate": "

http://www.google.com/search/hl=en&q=chicago

+style+pizza&start={index}&sa=N",

"items": [

{

"title": "Pizz'a Chicago Home Page"

// More fields for the search results

}

// More search results

]

}

}

這是如何展現螢幕截圖中的色塊的例子(背景顔色對應下圖中的顔色)

  • Results 11 - 20 of about 2,700,000 = startIndex
  • Results 11 - 20 of about 2,700,000 = startIndex + currentItemCount - 1
  • Results 11 - 20 of about 2,700,000 = totalItems
  • Search results = items (formatted appropriately)
  • Previous/Next = previousLink / nextLink
  • Numbered links in "Gooooooooooogle" = Derived from "pageLinkTemplate". The developer is responsible for calculating the values for {index} and substituting those values into the "pageLinkTemplate". The pageLinkTemplate's {index} variable is calculated as follows:
    • Index #1 = 0 * itemsPerPage = 0
    • Index #2 = 2 * itemsPerPage = 10
    • Index #3 = 3 * itemsPerPage = 20
    • Index #N = N * itemsPerPage

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E9%99%84%E5%BD%95 附錄

https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md#%E9%99%84%E5%BD%95ajavascript%E4%B8%AD%E7%9A%84%E4%BF%9D%E7%95%99%E5%AD%97 附錄A:JavaScript中的保留字

下列JavaScript保留字應該避免在屬性名中使用

下面的但在在JavaScript語言中被保留,不能作為在點通路符中使用。這份名單代表此時的最佳關鍵字的知識;清單可能會改變或根據您的特定的執行環境更改。

下面是JavaScript語言中的保留字,且不能在點通路符中使用。這份清單集合了目前最新的關鍵字,該清單可能會根據具體的執行環境而有所變更或改變。

來自

ECMAScript 語言規範第五版
abstract
boolean break byte
case catch char class const continue
debugger default delete do double
else enum export extends
false final finally float for function
goto
if implements import in instanceof int interface
let long
native new null
package private protected public
return
short static super switch synchronized
this throw throws transient true try typeof
var volatile void
while with
yield           

文章之外請關注

RDIFramework.NET官方網站:

http://www.rdiframework.net/

RDIFramework.NET官方部落格:

http://blog.rdiframework.net/

同時需要說明的,以後的所有技術文章以官方網站為準,歡迎大家收藏!

RDIFramework.NET架構由專業團隊長期打造、一直在更新、一直在更新,請放心使用!

歡迎關注RDIFramework.NET架構官方公衆微信(微信号:rdiframework-net),及時了解最新動态。

掃描二維碼立即關注

繼續閱讀