Обсуждение: Checking if a json-typed column contains a key

Поиск
Список
Период
Сортировка

Checking if a json-typed column contains a key

От
Wells Oliver
Дата:
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)

--

Re: Checking if a json-typed column contains a key

От
Paul Jungwirth
Дата:
> 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.