【问题标题】:Fetching array data from jsonb postgresql从 jsonb postgresql 获取数组数据
【发布时间】:2020-10-28 15:37:27
【问题描述】:

我很难从给定数组的 jsonb 中获取值。

{
    "question1": [
        "A",
        "B",
        "C"
    ],
    "question2": [
        "D",
        "E",
        "F"
    ],
    "question3": "G",
}

对于 question3,我可以将 value 作为 column_name ->> 'question3'::text 获取,并且我将 value 作为 "G" 但在 question1 和 question2 的情况下,我想以数组的形式获取值并检查 question1 数组或 question2 数组中是否存在特定元素。

【问题讨论】:

  • 是否要返回完整的列内容,但只返回数组中存在值的行?还是您只想返回包含该元素的数组(即只是完整 JSON 的一部分)。
  • 您使用的是哪个 Postgres 版本?

标签: postgresql


【解决方案1】:

如果只想过滤JSON数组中存在特定值的行,可以使用contains运算符@>:

select *
from the_table
where the_column -> 'question1' @> '["A"]'
   or the_column -> 'question2' @> '["A"]'

【讨论】:

    【解决方案2】:

    使用 postgres json 函数 jsonb_array_elements / json_array_elements (link here) 会得到结果。 jsonb_array_elements(column_name -> 'question1')

    【讨论】:

      【解决方案3】:

      您可以检查获取的 json 值的类型并据此采取行动:如果它是字符串,那么您可以简单地打印它,或者如果它是数组,那么您可以继续并在 json 数组中搜索一个元素。

       with tempJ(json_col) as (values('{"question1":[ "A", "B", "C" ], "question2":[ "D", "E", "F" ], "question3":"G"}'::jsonb))
        SELECT case jsonb_typeof(json_col->'question2')
                    when 'array' then (json_col->'question2')
                    else (json_col->'question2') end
        from tempJ    
      
      

      要从数组中搜索元素,您可以使用:

      select '[ "A", "B", "C" ]'::jsonb @> '"A"'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-24
        • 2017-09-11
        • 1970-01-01
        • 1970-01-01
        • 2019-09-26
        • 1970-01-01
        相关资源
        最近更新 更多