Re: JSON in 9.2 - Could we have just one to_json() function instead of two separate versions ?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Hannu Krosing <hannu(at)2ndQuadrant(dot)com>
Cc: Robert Haas <robertmhaas(at)gmail(dot)com>, Andrew Dunstan <andrew(at)dunslane(dot)net>, PostgreSQL-development <pgsql-hackers(at)postgresql(dot)org>, Merlin Moncure <mmoncure(at)gmail(dot)com>
Subject: Re: JSON in 9.2 - Could we have just one to_json() function instead of two separate versions ?
Date: 2012-05-05 15:49:37
Message-ID: 13188.1336232977@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hannu Krosing <hannu(at)2ndQuadrant(dot)com> writes:
> CAST is something that should convert one type to another, in this case
> a textual type to its "json value" representation and back.
> 'sometext'::text::json --> '"sometext"'
> and
> '"sometext"'::json::text --> 'sometext'

Well, that's a pretty interesting example, because if you expect that to
work like that, then what should happen with this?

'{"f1":4,"f2":2}'::text::json
'{"f1":4,"f2":2}'::json::text

Does the first of these produce a JSON object, or a quoted string?
At the moment you get the former, but it's pretty hard to argue that
it shouldn't produce a quoted string if transparent conversion is the
expectation. In the second case, do you end up with a JSON text (which
is what happens at the moment) or does it just slap some quotes around
the value as a string? I'm not convinced that you've made a principled
argument as to what should happen when.

In general, I think casts should only be used for conversions where
there is just one unsurprising choice of behavior, since the cast syntax
by definition doesn't provide any room for options. It's not clear to
me that JSON conversions are so obvious as to meet that standard. If
you start throwing random user-defined conversions into the mix, it's
even less obvious that there's only one unsurprising choice.

In the particular case of casts to and from text, we've essentially
set a project policy that those should behave equivalently to the type's
I/O conversion functions whenever possible. So I think the existing
behavior of those operations is correct and what you propose above is
wrong. There is certainly scope for a conversion function that takes
any random text string and produces a JSON quoted string from it, but
the cast operator is not the place for that.

regards, tom lane

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Tom Lane 2012-05-05 16:08:00 Re: remove dead ports?
Previous Message Bruce Momjian 2012-05-05 15:37:27 Re: remove dead ports?