0

What would be the right way of getting Ajax, i.e. the value for the last occurence for key child1Dob1, from a json field that has a data structure that looks like the below,

{
  "data": {
    "data": {
      "data": {
        "child1Dob1": "Andy"
      },
      "child1Dob1": "Bob"
    },
    "child1Dob1": "Rick"
  },
  "child1Dob1": "Ajax"
}

The below query was an attempt from a similar question but i am getting a null value, so obviously i am missing something.

SELECT JSON_EXTRACT(`containerValue`,CONCAT("$.data[",JSON_LENGTH(`containerValue` ->> '$.data')-1,"]")) from myTable where containerKey = 'theContainer';
2
  • the last occurence for child1Dob1 What is "the last"? the object properties are not ordered (rather than array elements). The most inner? use recursive CTE.. Commented Apr 15, 2022 at 6:03
  • correct, the most inner would be another way of describing it Commented Apr 15, 2022 at 6:05

1 Answer 1

1

For CREATE TABLE test (data JSON):

WITH RECURSIVE 
cte AS (
  SELECT data, data -> '$.data' subdata
  FROM test
  UNION ALL
  SELECT subdata, subdata -> '$.data' 
  FROM cte
  WHERE subdata IS NOT NULL
)
SELECT data ->> '$.child1Dob1'
FROM cte
WHERE subdata IS NULL;
Sign up to request clarification or add additional context in comments.

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.