【问题标题】:postgres find whether json path existspostgres 查找json路径是否存在
【发布时间】:2016-09-05 18:41:13
【问题描述】:

我想使用 psql 查询查找 jsonb 值中是否存在特定路径。

例如,对于这个路径:{"333":"opc":["1333"]}

这个值应该返回 true:

'{"333":{"opc":[{"1333":"3787"}]}}'

但这些值应该返回 false:

  • '{"333":{"opc":[{"104":"3787"}]}}'
  • '{"54":{"opc":[{"1333":"3787"},{"1334":"37"}]}}'
  • '{"333":{"opc":[]}}'

我尝试了一些使用 @> 运算符的变体,但无法完全获得正确的语法。

例如:

select 
  '{"333":{"opc":[{"1333":"3787"},{"1334":"37"}]}}'::jsonb @>   
  '{"333":{"opc":[{"1333"}]}}'::jsonb

这给了我一个无效的语法错误

【问题讨论】:

    标签: json postgresql path psql jsonb


    【解决方案1】:

    怎么样

    select 
      case when
        (select e->'1333' from json_array_elements(data->'333'->'opc') e) is not null
        then true
        else false
      end as status
    from t 
    ;
    

    http://sqlfiddle.com/#!15/2c794/17

    【讨论】:

    • 感谢您抽出宝贵时间回复。当我尝试您的建议时,我收到以下错误...错误:用作表达式的子查询返回的行不止一行。让我再测试一下,我会再次发布。
    • 感谢您的回复。我最终使用了这个: select * from (select jsonb_array_elements(data->'333'->'opc')->'1333' as value from t ) e where e.value is not null
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 2018-01-10
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    相关资源
    最近更新 更多