2

I have an issue where I have some JSON stored in my oracle database, and I need to extract values from it.

The problem is, there are some fields that are duplicated.

When I try this, it works as there is only one firstname key in the options array:

    SELECT 
    JSON_VALUE('{"increment_id":"2500000043","item_id":"845768","options":[{"firstname":"Kevin"},{"lastname":"Test"}]}', '$.options.firstname') AS value
   FROM DUAL;

Which returns 'Kevin'.

However, when there are two values for the firstname field:

SELECT JSON_VALUE('{"increment_id":"2500000043","item_id":"845768","options":[{"firstname":"Kevin"},{"firstname":"Okay"},{"lastname":"Test"}]}', '$.options.firstname') AS value
  FROM DUAL;

It only returns NULL.

Is there any way to select the first occurence of 'firstname' in this context?

3 Answers 3

1

JSON_VALUE returns one SQL VALUE from the JSON data (or SQL NULL if the key does not exists).

If you have a collection of values (a JSON array) an you want one specific item of the array you use array subscripts (square brackets) like in JavaScript, for example [2] to select the third item. [0] selects the first item. To get the first array item in your example you have to change the path expression from '$.options.firstname' to '$.options[0].firstname'

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

Comments

0

You can follow this query:-

SELECT JSON_VALUE('{
  "increment_id": "2500000043",
  "item_id": "845768",
  "options": [
    {
      "firstname": "Kevin"
    },
    {
      "firstname": "Okay"
    },
    {
      "lastname": "Test"
    }
  ]
}', '$.options[0].firstname') AS value
  FROM DUAL;

Comments

0

If there is a multiple node and you would like to search for an object in the array list.

  1. Create Type and Table
CREATE OR REPLACE TYPE "TY_OPTION" IS OBJECT
(
  FIRSTNAME         VARCHAR(255)
)

CREATE OR REPLACE TYPE "TBL_OPTION" AS TABLE OF TY_OPTION
  1. Create query select the array object.
SELECT *
FROM   TABLE (SELECT JSON_VALUE('{"increment_id":"2500000043","item_id":"845768","options":[{"firstname":"Kevin"},{"lastname":"Test"}]}', '$.options'
                                 RETURNING
                                 TBL_OPTION) UDF
              FROM   DUAL)

By combining the technique of type object and type table, we can select the JSON array object into the type table as a temporary table where you could put more conditions on the JSON array object and select the interested / target column as the output of the query.

Comments

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.