Extract json array from postgres table gives error: cannot extract elements from a scalar

后端 未结 2 1563
礼貌的吻别
礼貌的吻别 2021-02-20 04:23

By using jsonb_array_elements() function to extract out jsonb data array from Postgres, it gave error:

cannot extract elements f

2条回答
  •  离开以前
    2021-02-20 04:53

    After some research I see there was a change at PostgreSQL 10 that broke the original answer.

    Here is how I did the example in 10.

    select jsonb_array_elements(test.date) as date
    from
    (select
      case when jsonb_typeof(jsonb_column->'stats_by_date'->'date') = 'array'
           then jsonb_column->'stats_by_date'->'date'
           else jsonb_build_array(jsonb_column->'stats_by_date'->'date')
      end as date
    from (
      select '{"stats_by_date": {"date": 123}}'::jsonb -- scalar (type: 'number')
      union all
      select '{"stats_by_date": {"date": [456]}}'::jsonb -- array (type: 'array')
      ) foo(jsonb_column)) as test;
    

提交回复
热议问题