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

后端 未结 5 540
忘掉有多难
忘掉有多难 2021-02-06 01:10

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?
--------         


        
5条回答
  •  悲&欢浪女
    2021-02-06 01:38

    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.

提交回复
热议问题