回答

收藏

如何查询JSON列中的空对象?

技术问答 技术问答 63 人阅读 | 0 人回复 | 2023-09-13

寻找所有的行,其中某个json列包含一个空对象{}。对于JSON数组,或者在对象中寻找特定键,这是可能的。但是我只想知道对象是否为空。似乎找不到可以执行此操作的运算符。8 N. ]2 c7 Z9 Z6 x
dev=# \d test
4 A# G5 J2 Z2 G( i# _- i" U     Table "public.test"' p" O4 l0 l9 x; d- M6 F
  Column | Type | Modifiers
  w9 D& [& f9 R --------+------+-----------% v3 a& v; P7 k! z; J5 B) G; A' O
  foo    | json |* E( L+ m& s; H# ^9 ?
dev=# select * from test;
1 e5 I) k1 @( g4 G    foo
# U0 U  ~! j# u5 x5 A  A ---------6 h0 C9 D# ^* @1 U, a( t7 U
  {"a":1}/ z* J& n" _' |  |" F* R% a* \8 Q0 m
  {"b":1}
7 ]0 U4 ~! V8 M9 A# N: {: C$ w  {}; i; x- I# h) E& Z9 x7 Z1 l
(3 rows), A; a9 u0 w  n. g5 d. P) J7 M, w
dev=# select * from test where foo != '{}';
5 f5 T( ?% m# Z/ _" C( g ERROR:  operator does not exist: json  unknown
) Q. U' Z1 l, Z! ^" M0 O LINE 1: select * from test where foo != '{}';
9 j2 ^# Q; N) N" M                                      ^3 n- l# p2 L1 Q+ M$ p4 _
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.5 L  |$ j/ F7 n4 m$ H; i; v* u
dev=# select * from test where foo != to_json('{}'::text);( R' S/ k1 d1 ~
ERROR:  operator does not exist: json  json. S: d, J7 [4 W  V( d
LINE 1: select * from test where foo != to_json('{}'::text);
2 h8 o0 E  r  {9 S* d6 R                                      ^" ^$ z: f) Q+ ^8 D
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
% w3 ?7 `8 _& `* ^$ O9 X/ A5 h dwv=# select * from test where foo != '{}'::json;: r9 f. M1 i2 U! T! Q$ o# g0 S
ERROR:  operator does not exist: json  json2 W, S+ N: U0 [
LINE 1: select * from test where foo != '{}'::json;
( m! g: z0 k$ ?" I- `                                      ^. c4 H+ i- y0 ?, F5 i  Z4 h' \
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
  w. Q: v8 u" D% }3 X+ o               
2 b+ A: D. G5 ~5 R解决方案:" v6 _6 S9 y( _9 s: l
                % }$ h( r5 e6 k) t8 x  d. ?

3 _4 [; r4 l2 D9 J+ T' o) c8 A! H" V3 s8 P9 z
                有没有平等(或等于)运算符的数据类型json作为一个整体,因为平等是很难建立。jsonb在可行的情况下,请考虑使用Postgres 9.4或更高版本。有关dba.SE(上一章)的此相关答案中的更多详细信息:
. l0 h* }: V* t- I4 a如何从PostgreSQL的JSON []数组中删除已知元素?
0 D% [- x3 ~  j  `4 j+ k5 XSELECT DISTINCT json_column ...或... GROUP BY json_column由于相同原因而失败(没有相等运算符)。; H+ Q" r' \& [" l* c4 H3 ?
将表达式的两边都转换为textallow=或operator,但这通常并不可靠,因为对于相同的JSON值,有很多可能的文本表示形式。
# O! t# B! P( k但是,对于这种特殊情况(空对象),它可以正常工作:. _: R5 v! j2 p$ ^0 q& i* D
select * from test where foo::text  '{}'::text;
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则