0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PostgreSQL で SELECT 結果を JSON 形式で出力

Posted at

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]"}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?