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

From: Paul Jungwirth <pj(at)illuminatedcomputing(dot)com>
To: Wells Oliver <wellsoliver(at)gmail(dot)com>
Cc: "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: Checking if a json-typed column contains a key
Date: 2015-02-01 00:49:47
Message-ID: CA+6hpa=UfyzpFrhhVTr8Wu_hba4xkKGK=W6-60rDL+9=OvHYvw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

> 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.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Álvaro Hernández Tortosa 2015-02-01 14:54:03 Re: Fwd: [GENERAL] 4B row limit for CLOB tables
Previous Message Wells Oliver 2015-01-31 23:23:27 Checking if a json-typed column contains a key