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

后端 未结 5 485
忘掉有多难
忘掉有多难 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:32

    If you want to filter multiple rows with JSONB documents in each of them:

    -- Let's generate rows with JSONB column:
    WITH s AS (SELECT generate_series(1, 100) num),
    g AS (SELECT num, jsonb_build_object('a', s.num, 'b', s.num * 2) obj FROM s),
    
    -- A "filter" adding (in my example only keys of "filter" document remain in result rows)
    j AS (SELECT '{"a": "int", "c": "string"}'::jsonb AS filter),
    a AS (SELECT (ARRAY(SELECT jsonb_object_keys(filter))) AS ar FROM j),
    
    -- Useless keys removing
    o AS (SELECT jsonb_object_agg(l.key, l.value) obj
            FROM g, LATERAL jsonb_each(g.obj) l, a 
            WHERE l.key = ANY(a.ar)
            GROUP BY num)
    
    SELECT * FROM o ORDER BY obj->'a';
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-06 01:36

    You can do this

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

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

    select '{"a": 1, "b": 2, "c":3}'::jsonb->>'a'
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-06 01:45

    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/

    0 讨论(0)
提交回复
热议问题