2014-06-18 120 views
29

尋找找到某個json列包含空對象的所有行,{}。這可以用JSON數組,或者如果我正在尋找對象中的特定鍵。但我只想知道對象是否爲空。似乎無法找到一個能夠做到這一點的運營商。如何查詢空對象的json列?

dev=# \d test 
    Table "public.test" 
    Column | Type | Modifiers 
--------+------+----------- 
    foo | json | 

dev=# select * from test; 
    foo 
--------- 
    {"a":1} 
    {"b":1} 
    {} 
(3 rows) 

dev=# select * from test where foo != '{}'; 
ERROR: operator does not exist: json <> unknown 
LINE 1: select * from test where foo != '{}'; 
            ^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. 
dev=# select * from test where foo != to_json('{}'::text); 
ERROR: operator does not exist: json <> json 
LINE 1: select * from test where foo != to_json('{}'::text); 
            ^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. 
dwv=# select * from test where foo != '{}'::json; 
ERROR: operator does not exist: json <> json 
LINE 1: select * from test where foo != '{}'::json; 
            ^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. 

回答

55

不相等(或不等式),用於作爲一個整體的數據類型json操作者,因爲平等是難以建立。你會jsonb在Postgres 9.4,這是可能的。更多細節在這個相關的答案上dba.SE(最後一章):

鑄造表達的兩側text允許=<>運營商,但是這不是正常可靠,有許多可能的文本表示爲相同json值。

對於這種特殊的情況下,雖然,它工作得很好:

select * from test where foo::text <> '{}'::text; 
+0

新鮮出爐:http://www.postgresql.org/about/news/1557/ – opyate

+2

可能很明顯,但這適用於空陣列以及用[] – hobberwickey

+1

代替{}如果您正在尋找嵌套結構,下面可能是你可以使用的東西:'select * from test where foo - >>'property'='[]';'結構可能類似於:'{「property」:[],「 foo「:」bar「}' – Dynom

1

在9.3,可以計算每個對象中的對與沒有

create table test (foo json); 
insert into test (foo) values 
('{"a":1, "c":2}'), ('{"b":1}'), ('{}'); 

select * 
from test 
where (select count(*) from json_each(foo) s) = 0; 
foo 
----- 
{} 

或測試篩選那些存在,對於大物體可能更快

select * 
from test 
where not exists (select 1 from json_each(foo) s); 

這兩種技術都可以完美地工作rega無格式化

+0

爲什麼在這些示例中調用json_each之後的's'?它的用途是什麼? – Stratus3D

+0

@ Stratus3D這是子查詢的強制別名,在這種情況下是函數。 –