1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

postgresql9.5.1でjsonの基本操作。追加更新できるようになった。

Last updated at Posted at 2016-03-10

環境
postgresql 9.5.1
psql 9.5.1

マークダウンで再編集。

参考ドキュメント
https://www.postgresql.jp/document/9.5/html/functions-json.html

jsonbを基本使う。
jsonは、配列の並びが固定なので、フィールドをナンバーインデックス指定して使うなら使えそうだけど、基本はjsonb型推奨。

create
create table test (DATA JSONB);
insert
testuser=# insert into test values ('{"id":"0","id_old":"1"}'::jsonb) returning *;
            data            
----------------------------
 {"id": "0", "id_old": "1"}

9.4からJSONBデータでJSONデータに要素が含まれるか確認可能になる
存在演算子:idキーがあるかチェック

keycheck
testuser=# select data?'id' from test;
 ?column? 
----------
 t
(1 )

9.5からvalueの追加更新が可能になる、

json.update
testuser=# select data||'{"id":"2"}'::jsonb from test;
          ?column?          
----------------------------
 {"id": "2", "id_old": "1"}

値の取得は、

value.get
testuser=# select data->'id' from test;
 ?column? 
----------
 "0"

値の取得は、ネストでも取れる。

value.nest.get
testuser=# select  '{"a": {"b":"foo"}}'::json->'a'->'b';
 ?column? 
----------
 "foo"

今日はここまで。
amazon rdsも9.5に早く対応するといいなー。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?