2016-09-14 4 views
2

PostgreSQL(バージョン9.3)jsonオブジェクトのブール値を文字列に変換せずに一致させる方法はありますか?PostgreSQL 9.3 jsonオブジェクトのブール値の比較

私は何を意味している:

を:

'{"path":"mypath", "exists": true}' 

は、次のクエリは、レコード(exists値は->>とテキストとしてフェッチであることに注意)を取り出し: 表には、そのjsoncolumn列に次のオブジェクトが含まれています

select * from thetable where jsoncolumn ->> 'exists' = 'true'; 

とこれはしていません:

select * from thetable where jsoncolumn -> 'exists' = true; 

ブール比較を行うより適切な方法があるのだろうか?

+0

は、あなたがしようとしました: '(jsoncolumn - > 'exists'):: boolean = true'? –

+0

@a_horse_with_no_nameはい、あります。どちらもうまくいかなかった。 – BanzaiTokyo

答えて

0

テキストとして値を取得しますが、その後ブール値にキャスト:

select pg_typeof((j ->> 'exists')::boolean) 
from (values ('{"path":"mypath", "exists": true}'::json)) v(j) 
; 
pg_typeof 
----------- 
boolean 

Valid boolean literals

+0

私の質問は、ブール値かどうかをチェックするのではなく、値が真であるかどうかを調べる方法です。申し訳ありませんが私の質問から不明だった場合。 – BanzaiTokyo

+0

これは、jsonではなくブール値を取得する方法を示したものです。意図どおりに使用することができます。 –

2

Here're(b)はブールJSONを検証するために、すべての有効な組み合わせ:

-- This works only with jsonb, not with json because in Postgres json type is just a string. 
SELECT $${ "exists": true }$$::jsonb -> 'exists' = 'true'; 
-[ RECORD 1 ] 
?column? | t 

-- All the following works with regular json as well with jsonb: 
SELECT ($${ "exists": true }$$::json ->> 'exists')::boolean; 
-[ RECORD 1 ] 
bool | t 

SELECT ($${ "exists": true }$$::json ->> 'exists')::boolean IS TRUE; 
-[ RECORD 1 ] 
?column? | t 

SELECT ($${ "exists": true }$$::json ->> 'exists')::boolean = TRUE; 
-[ RECORD 1 ] 
?column? | t 
関連する問題