2016-08-30 2 views
4

에서 요소를 추출 할 수 있고, 이는 에러를 준 반환 전화에서 NULLNULL 조건을 검사했지만 작동하지 않습니다. 어떤 도움을 주셔서 감사합니다. 데이터에추출 JSON 배열 오류 준다 : 그것은 때문이다 가정</p> <blockquote> <p>cannot extract elements from a scalar</p> </blockquote> <p>: 포스트 그레스에서 <code>jsonb</code> 데이터 배열을 추출 <code>jsonb_array_elements()</code> 기능을 이용하여 스칼라

"stats_by_date": {"date": [16632, 16633, 16634, ...], "imps": [2418, 896, 1005...], ...}

+0

샘플 json 값을 입력하십시오. 오류가 꽤 분명 보인다. 'jsonb_array_elements'에 전달 된 값은 json 배열이 아닌 스칼라입니다. –

+0

"stats_by_date": { "date": [16632, 16633, 16634, 16635, 16636, 16637, 16638, 16639, 16637, 16638, 16639, 16640, 16641, 16642, 16643, 16644, 16645, 16646, 16647, 16648, 16649, 16650, 16651 , 16652, 16653, 16654, 16655, 16656, 16657, 16658, 16659, 16660, 16661, 16662, 16663, 16664, 16665, 16666, 16667, 16668, 16669, 16670, 16671, 16672, 16673, 16674] ": [2418, 896, 1005 ...], ...} –

+0

모든 데이터 테이블에서 루프가 실행되면 오류가 발생하여 null/스칼라가 전달 될 수 있습니다. 'jsonb_array_elements' 함수에 추가합니다. 확인하고 우회하는 방법을 알고 싶습니다. –

답변

3

대신 date 키 내부 배열의 일부 스칼라 값이 있어야합니다 : 같은

select id , 
    CASE 
    WHEN report IS NULL OR 
     (report->'stats_by_date') IS NULL OR 
     (report->'stats_by_date'-> 'date') IS NULL then to_json(0)::jsonb 
    ELSE jsonb_array_elements(report -> 'stats_by_date' -> 'date') 
    END AS Date 
    from factor_reports_table 

절단 된 JSON 배열 보인다.

jsonb_typeof()과 함께 특정 키 유형을 식별 한 다음 CASE 문 내에 마무리 할 수 ​​있습니다. 귀하의 의견은 설정으로

스칼라와 배열의 예를 아래에 고려하십시오

select 
    case when jsonb_typeof(jsonb_column->'stats_by_date'->'date') = 'array' 
     then jsonb_array_elements(jsonb_column->'stats_by_date'->'date') 
     else 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); 

결과 따라서 쿼리가 필요

date 
------ 
123 
456 

가 이러한 경우 처리하기 위해 다음과 같이 쓸 수 :

select id, 
    case when jsonb_typeof(jsonb_column->'stats_by_date'->'date') = 'array' 
     then jsonb_array_elements(jsonb_column->'stats_by_date'->'date') 
     else jsonb_column->'stats_by_date'->'date' 
    end as date 
from factor_reports_table 
+0

그게 효과가 있습니다! 고마워. –