PostGreSQL 從 9.2 開始增加對 JSON 的支持。9.5 已經支持多個 JSON 函數,見 http://www.postgres.cn/docs/9.5/functions-json.html
關於如何查詢返回 JSON,這里 有例子,翻譯如下:
一個簡單的用法就是使用 row_to_json() 函數,它接受 “行值”並返回 JSON 對象:
select row_to_json(tableName) from tableName;
上面查詢語句返回結果類似如下:
{"id":6013,"text":"advancement","pronunciation":"advancement",...}
但是有時候我們只需要查詢指定的列,那么我們可以使用 row() 結構函數:
select row_to_json(row(id, text)) from
tableName;
上面查詢語句返回了我們想要的結果,可惜丟失了列名:
{"f1":6013,"f2":"advancement"}
為了完善這個需求,我們必須創建一個行類型且將結果轉換(cast)到這個行類型,或者使用子查詢。子查詢會更容易一些:
select row_to_json(t) from ( select id, text from tableName ) AS t
上面查詢語句返回了我們希望的樣子:
{"id":6013,"text":"advancement"}
另一種常用的技術是 array_agg 和 array_to_json。array_agg 是一個聚合函數 sum 或 count。它聚集成一個 PostgreSQL 數組參數。array_to_json 以 PostgreSQL數組 拼合成一個單一的JSON值。
我們來看看 array_to_json 的用法:
select array_to_json(array_agg(row_to_json(t))) from ( select id, text from tableName ) AS t
上面查詢語句返回了一個由 JSON 對象組成的數組:
[{"id":6001,"text":"abaissed"},{"id":6002,"text":"abbatial"},{"id":6003,"text":"abelia"},...]
我們來一個復雜的例子(注:這個例子可能有問題):
select row_to_json(t) from ( select text, pronunciation, ( select array_to_json(array_agg(row_to_json(d))) from ( select part_of_speech, body from definitions where word_id=words.id order by position asc ) d ) as definitions from words where text = 'autumn'
上面查詢語句返回結果如下:
{ "text": "autumn", "pronunciation": "autumn", "definitions": [ { "part_of_speech": "noun", "body": "skilder wearifully uninfolded..." }, { "part_of_speech": "verb", "body": "intrafissural fernbird kittly..." }, { "part_of_speech": "adverb", "body": "infrugal lansquenet impolarizable..." } ] }
Obviously, the SQL to generate this JSON response is far more verbose than generating it in Ruby. Let's see what we get in exchange.(怎么突然蹦出個 Ruby ?)
性能測試