retrieve subset of a jsonb object with a list of keys

Started by Tom Smithover 10 years ago3 messagesgeneral
Jump to latest
#1Tom Smith
tomsmith1989sk@gmail.com

Hi:

I have a jsonb columne with json object like belo
{"a": 1, "b":2, "c":3}

I'd like to get subset of the object with key list ["a","c"]
so it retruns json object of

{"a": 1, "c":3}

something like

select '{"a": 1, "b":2, "c":3}'::jsob ->'["a","c"]'

what would be the most efficient (and simplest if possible) to get the
subset with the key list?

Thanks

#2Chris Mair
chris@1006.org
In reply to: Tom Smith (#1)
Re: retrieve subset of a jsonb object with a list of keys

On 19/08/15 13:37, Tom Smith wrote:

Hi:

I have a jsonb columne with json object like belo
{"a": 1, "b":2, "c":3}

I'd like to get subset of the object with key list ["a","c"]
so it retruns json object of

{"a": 1, "c":3}

something like

select '{"a": 1, "b":2, "c":3}'::jsob ->'["a","c"]'

what would be the most efficient (and simplest if possible) to get the
subset with the key list?

Hi,

I came up with this:

select json_object_agg(key, value)
from jsonb_each_text('{"a": 1, "b":2, "c":3}'::jsonb)
where key in ('a', 'c');

IDK if there is a shorter way. You might want to wrap this in a function.

Bye,
Chris.

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

#3Tom Smith
tomsmith1989sk@gmail.com
In reply to: Chris Mair (#2)
Re: retrieve subset of a jsonb object with a list of keys

thanks. I hope a new function can be added(with high perf C function) in
new release to allow something like

json_subset(jsonb_object, [key1,key2])

On Wed, Aug 19, 2015 at 9:46 AM, Chris Mair <chris@1006.org> wrote:

Show quoted text

On 19/08/15 13:37, Tom Smith wrote:

Hi:

I have a jsonb columne with json object like belo
{"a": 1, "b":2, "c":3}

I'd like to get subset of the object with key list ["a","c"]
so it retruns json object of

{"a": 1, "c":3}

something like

select '{"a": 1, "b":2, "c":3}'::jsob ->'["a","c"]'

what would be the most efficient (and simplest if possible) to get the
subset with the key list?

Hi,

I came up with this:

select json_object_agg(key, value)
from jsonb_each_text('{"a": 1, "b":2, "c":3}'::jsonb)
where key in ('a', 'c');

IDK if there is a shorter way. You might want to wrap this in a function.

Bye,
Chris.