0

I have json data and I am trying to put that data in different columns in oracle. Issue is one of the column sometimes contains an array and sometimes contain string. I know there is different command to put json array to column but if the column is populated with string sometimes and array sometimes, how do I write sql so that it fetch all data -

SELECT id,array1
FROM   (
  select '{
    "data": [
      {
        "id": 1,
        "array1": [ "INFO", "ABC", ]
      },
      {
        "id": 2,
        "array1": "TEST",
      }
    ]
  }' AS JSON_DATA
  FROM DUAL
) I,
json_table(
  i.JSON_DATA ,
  '$.data[*]'  
  COLUMNS (
    array1 varchar2(4000) FORMAT JSON path'$."array1"',
    ID     varchar2(4000) path '$."id"'
  )  
) a 

Output from the sql:

ID  ARRAY1
1   ["INFO","ABC"]
2   

Desired Ouput :

ID  ARRAY1
1   ["INFO","ABC"]
2   TEST

1 Answer 1

2

array1 varchar2(4000) PATH '$."array1"' can be considered together with

array1 varchar2(4000) FORMAT JSON PATH '$."array1"'

Since both case exists for values of array1 key. So, use :

SELECT ID, NVL(array1, array1_) AS array1
  FROM   
  (
   SELECT '{
        "data": [

          {
            "id": 1,
            "array1": [ "INFO", "ABC" ]
          },
          {
            "id": 2,
            "array1": "TEST"
          }
        ]
      }' AS JSON_DATA
     FROM DUAL
     ) I
    CROSS JOIN 
    JSON_TABLE(
      i.JSON_DATA ,
      '$.data[*]'  
      COLUMNS (
           array1  varchar2(4000) PATH '$."array1"',
           array1_ varchar2(4000) FORMAT JSON PATH '$."array1"',
           ID      varchar2(4000) PATH '$."id"'
      )  
     ) A

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks !! I was also thinking same. was wondering is there any alternate than to do nvl

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.