Checking if a json-typed column contains a key

Started by Wells Oliverabout 11 years ago2 messagesgeneral
Jump to latest
#1Wells Oliver
wellsoliver@gmail.com

With the hstore you can do hstore ? 'key' to check if the object contains
the key-- is there a similar function for json objects?

(still on 9.3 so no jsonb)

--
Wells Oliver
wellsoliver@gmail.com

#2Paul Jungwirth
pj@illuminatedcomputing.com
In reply to: Wells Oliver (#1)
Re: Checking if a json-typed column contains a key

With the hstore you can do hstore ? 'key' to check if the object contains
the key-- is there a similar function for json objects?

Is this good enough?:

=> select ('{"a":1,"b":null}'::json) -> 'a';
?column?
----------
1

=> select ('{"a":1,"b":null}'::json) -> 'b';
?column?
----------
null

=> select ('{"a":1,"b":null}'::json) -> 'c';
?column?
----------
NULL

=> select (('{"a":1,"b":null}'::json) -> 'a') IS NULL;
?column?
----------
f

Time: 0.334 ms
=> select (('{"a":1,"b":null}'::json) -> 'b') IS NULL;
?column?
----------
f

=> select (('{"a":1,"b":null}'::json) -> 'c') IS NULL;
?column?
----------
t

If you want to treat {"b":null} and absence of "b" the same way you
can use ->> instead of ->.

This does seem worrisome though:

=> select (('{"a":1, "b":null}'::json) -> 'b')::text;
text
------
null

I think json_typeof solves that in 9.4, but I don't see anything in
9.3 other than ->>.

Paul

--
_________________________________
Pulchritudo splendor veritatis.

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general