PostgreSQL の psql コマンドで select した結果を JSON 形式で出力する方法のメモ。
row_to_json() による JSON 形式での出力
-t オプションで select の出力結果にカラム名や区切り線が含まれなくなる。
また、-A オプションで不要な空白を抑止することができる。
$ psql -t -A -d db_test
row_to_json(テーブル名) でテーブルの全フィールドを出力することができる。
db_test=# select row_to_json(test1_author) from test1_author;
{"id":8,"name":"book1_author","target_id":8,"target_type_id":8}
{"id":9,"name":"book2_author","target_id":9,"target_type_id":8}
{"id":10,"name":"article1_author","target_id":7,"target_type_id":7}
{"id":11,"name":"article2_author","target_id":8,"target_type_id":7}
row_to_json(row(...)) でフィールドの値を加工して出力することができる。
ただし、フィールド名が f1, f2, ... となる。
db_test=# select row_to_json(row(id, concat('[', name, ']'))) from test1_author;
{"f1":8,"f2":"[book1_author]"}
{"f1":9,"f2":"[book2_author]"}
{"f1":10,"f2":"[article1_author]"}
{"f1":11,"f2":"[article2_author]"}