如何只从postgres获取特定键的jsonb?

时间:2017-09-29 18:23:37

标签: postgresql

我知道你可以使用类似这样的东西从postgres中的jsonb中删除键

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

有没有办法只抓取特定的键?比如我只想获得'a'

的键值对

这样的事情?

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

编辑:将示例更改为显示我想从jsonb中获取多个键值对而不只是一对。

5 个答案:

答案 0 :(得分:5)

您可以非常轻松地过滤到单个键:

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

...或者您可以过滤到多个键:

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

或者在更复杂的条件下,如果你想:

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

只需阅读documentation即可轻松回答这些问题。

答案 1 :(得分:1)

你可以得到这样的价值:

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

如果必须,您可以手动将其转换回jsonb,或者可以通过数组,hstore或其他中间类型。这是“手动”方式

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

答案 2 :(得分:0)

我实际上发现这种方式适用于。

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

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

答案 3 :(得分:0)

如果您要在每个行中使用JSONB文档来过滤多行:

-- 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';

答案 4 :(得分:0)

您可以做到

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

对于上述查询,应该是

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