变量替换查询 postgres jsonb 对象

variable substitution querying postgres jsonb object

您好,我正在查询一个 JSONb 对象,其中搜索键取决于另一个 key/value 对的值。考虑以下示例:

select 
'{"a":"b","b":2}'::jsonb->'a',--b,
('{"a":"b","b":2}'::jsonb->'a')::text,--"b"
'{"a":"b","b":2}'::jsonb->('{"a":"b","b":2}'::jsonb->'a')::text--null, desired output is 2

不知何故,我需要将 "b" 取消引用到 json 搜索路径,例如 'b'

任何建议将不胜感激

您应该使用 ->> 运算符而不是 ->。有不需要的双引号:

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