Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 678
richard_d_sim Avatar asked Sep 29 '17 18:09

richard_d_sim


People also ask

How do I query JSON data in PostgreSQL?

Querying JSON dataPostgreSQL provides two native operators -> and ->> to help you query JSON data. The operator -> returns JSON object field by key. The operator ->> returns JSON object field by text.

What is the difference between JSON and Jsonb in Postgres?

The json data type stores an exact copy of the input text, which processing functions must reparse on each execution; while jsonb data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed.

What is Json_build_object?

json_build_object(VARIADIC "any") Builds a JSON object out of a variadic argument list. By convention, the argument list consists of alternating keys and values.


Video Answer


1 Answers

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.

like image 153
Mumbleskates Avatar answered Sep 18 '22 17:09

Mumbleskates