Re: Duplicate JSON Object Keys

From: "David E(dot) Wheeler" <david(at)justatheory(dot)com>
To: Andrew Dunstan <andrew(at)dunslane(dot)net>
Cc: Gavin Flower <GavinFlower(at)archidevsys(dot)co(dot)nz>, Robert Haas <robertmhaas(at)gmail(dot)com>, Alvaro Herrera <alvherre(at)2ndquadrant(dot)com>, Hannu Krosing <hannu(at)2ndquadrant(dot)com>, "pgsql-hackers(at)postgresql(dot)org Hackers" <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: Duplicate JSON Object Keys
Date: 2013-03-13 18:32:06
Message-ID: 3BA2E36E-70AD-4E1B-962E-5AC91A64E486@justatheory.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Mar 13, 2013, at 10:59 AM, Andrew Dunstan <andrew(at)dunslane(dot)net> wrote:

>> And my first cut at it won’t descend into sub-objects.
>
>
> The you wouldn't be doing it right. The whole thing about a recursive descent parser is that it's, well, recursive.

Right, but it would serve my immediate needs. I have a column that just stores key/value pairs with no nesting. So I know I can write something like this and have it be good enough:

create or replace function json_smash(
json
) RETURNS JSON language SQL STRICT IMMUTABLE AS $$
SELECT format('{%s}', array_to_string(ARRAY(
SELECT format('%s: %s', to_json(key), value)
FROM (
SELECT key, value, row_number() OVER (
partition by key order by rnum desc
) AS rnum
FROM (
SELECT key, value, row_number() OVER (
partition by key
) AS rnum
FROM json_each($1)
) a
) b
WHERE rnum = 1
), ','))::json;
$$;

And do you really want to see that unloosed on the world? :-P (Yes, I know there is no guarantee on the order of rows returned by json_each()).

Best,

David

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Tom Lane 2013-03-13 19:04:35 Re: Column defaults for foreign tables (was Re: [v9.3] writable foreign tables)
Previous Message Andrew Dunstan 2013-03-13 17:59:21 Re: Duplicate JSON Object Keys