Search code examples
postgresqljsonb

How to get only the jsonb of specific keys from postgres?


I'm aware that you can remove keys from a jsonb in postgres using something like this

select '{"a": 1, "b": 2, "c":3}'::jsonb -'a';
 ?column?
----------
{"b": 2 "c":3}
(1 row)

Is there a way to only grab specific keys? Like let's say I just want to get the key-value pair of just the 'a' key.

Something like this?

select '{"a": 1, "b": 2}'::jsonb + 'a' + 'b';
 ?column?
----------
{"a": 1, "b": 2}
(1 row)

EDIT: Changed the example to to show that I'd like to grab multiple keys-value pairs from the jsonb and not just one pair.


Solution

  • You can filter down to a single key fairly easily like so:

    jsonb_object(ARRAY[key, jsonb_data -> key])
    

    ...or you can filter down to multiple keys:

    (SELECT jsonb_object_agg(key, value) FROM jsonb_each(jsonb_data) WHERE key IN ('a', 'b'))
    

    Or on a more complex condition, if you want:

    (
      SELECT jsonb_object_agg(key, value)
      FROM jsonb_each(jsonb_data)
      WHERE
        key NOT LIKE '__%'
        AND jsonb_typeof(value) != 'null'
    )
    

    These kinds of questions can be answered very easily by simply reading the documentation.