potential bug in JSON

Started by Szymon Guzover 12 years ago4 messages
#1Szymon Guz
mabewlun@gmail.com

I've found a potential bug. Why the "->" operator returns JSON instead of
TEXT? It doesn't make sens for me, and the documentation doesn't inform
about that.

postgres=# SELECT ('{"id": 1}'::json -> 'id')::int;
ERROR: cannot cast type json to integer
LINE 1: SELECT ('{"id": 1}'::json -> 'id')::int;

postgres=# SELECT ('{"id": 1}'::json -> 'id')::text::int;
int4
------
1
(1 row)

postgres=# SELECT version();
version

---------------------------------------------------------------------------------------------------------------
PostgreSQL 9.3beta1 on x86_64-unknown-linux-gnu, compiled by gcc
(Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3, 64-bit
(1 row)

#2Andrew Dunstan
andrew@dunslane.net
In reply to: Szymon Guz (#1)
Re: potential bug in JSON

On 05/28/2013 11:38 AM, Szymon Guz wrote:

I've found a potential bug. Why the "->" operator returns JSON instead
of TEXT? It doesn't make sens for me, and the documentation doesn't
inform about that.

postgres=# SELECT ('{"id": 1}'::json -> 'id')::int;
ERROR: cannot cast type json to integer
LINE 1: SELECT ('{"id": 1}'::json -> 'id')::int;

postgres=# SELECT ('{"id": 1}'::json -> 'id')::text::int;
int4
------
1
(1 row)

This is not a bug. It is documented and by design.

If you want text, use the ->> operator. That's exactly what it's for.

cheers

andrew

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

#3Josh Berkus
josh@agliodbs.com
In reply to: Szymon Guz (#1)
Re: potential bug in JSON

On 05/28/2013 08:38 AM, Szymon Guz wrote:

I've found a potential bug. Why the "->" operator returns JSON instead of
TEXT? It doesn't make sens for me, and the documentation doesn't inform
about that.

Yes, it most certainly does:
http://www.postgresql.org/docs/9.3/static/functions-json.html

If you want to get text, use the ->> operator.

--
Josh Berkus
PostgreSQL Experts Inc.
http://pgexperts.com

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

#4Szymon Guz
mabewlun@gmail.com
In reply to: Josh Berkus (#3)
Re: potential bug in JSON

On 28 May 2013 17:53, Josh Berkus <josh@agliodbs.com> wrote:

On 05/28/2013 08:38 AM, Szymon Guz wrote:

I've found a potential bug. Why the "->" operator returns JSON instead of
TEXT? It doesn't make sens for me, and the documentation doesn't inform
about that.

Yes, it most certainly does:
http://www.postgresql.org/docs/9.3/static/functions-json.html

If you want to get text, use the ->> operator.

Yea, I noticed that. It was a little bit misleading for me that "->" is for
getting field and "->>" is for getting field as text. Especially when
"->"::TEXT doesn't return the same value as "->>".
Maybe there should be added "as JSON" to those operators which don't return
text?

Szymon