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

You can get just the value like so:

 select '{"a": 1, "b": 2}'::jsonb-> 'a';

If you must, you can transform that back into jsonb manually, or perhaps go through an array, hstore or other intermediate type. Here's the "manual" way

 select ('{ "a": '||('{"a": 1, "b": 2}'::jsonb->'a')::text||'}')::jsonb

I actually found that this way works to.

select jsonb_build_object('key', column->'key') from table;

reference: https://www.reddit.com/r/PostgreSQL/comments/73auce/new_user_to_postgres_can_i_grab_multiple_keys_of/


You can do this

SELECT jsonb_column->>'key_name_here' as 'alias_name_as_you_like' from table_name

In the case of the query asked above, it would be

select '{"a": 1, "b": 2, "c":3}'::jsonb->>'a'

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.

Tags:

Postgresql