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

From Tom Lane
Subject Re: JSON in 9.2 - Could we have just one to_json() function instead of two separate versions ?
Date
Msg-id 13188.1336232977@sss.pgh.pa.us
Whole thread Raw
In response to Re: JSON in 9.2 - Could we have just one to_json() function instead of two separate versions ?  (Hannu Krosing <hannu@2ndQuadrant.com>)
List pgsql-hackers
Hannu Krosing <hannu@2ndQuadrant.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


pgsql-hackers by date:

Previous
From: Bruce Momjian
Date:
Subject: Re: remove dead ports?
Next
From: Tom Lane
Date:
Subject: Re: remove dead ports?