Search code examples
mysqlmysql-json

How to deal with not existing values using JSON_EXTRACT?


I have a list ob objects. Each object contains several properties. Now I want to make a SELECT statement that gives me a list of a single property values. The simplified list look like this:

[
    [
        {
            "day": "2021-10-01",
            "entries": [
                {
                    "name": "Start of competition",
                    "startTimeDelta": "08:30:00"
                }
            ]
        },
        {
            "day": "2021-10-02",
            "entries": [
                {
                    "name": "Start of competition",
                    "startTimeDelta": "03:30:00"
                }
            ]
        },
        {
            "day": "2021-10-03",
            "entries": [
                {
                    "name": "Start of competition"
                }
            ]
        }
    ]
]

The working SELECT is now

SELECT
    JSON_EXTRACT(column, '$.days[*].entries[0].startTimeDelta') AS list
FROM table

The returned result is

[
    "08:30:00",
    "03:30:00"
]

But what I want to get (and also have expected) is

[
    "08:30:00",
    "03:30:00",
    null
]

What can I do or how can I change the SELECT statement so that I also get NULL values in the list?


Solution

  • SELECT startTimeDelta
    FROM test
    CROSS JOIN JSON_TABLE(val,
                          '$[*][*].entries[*]' COLUMNS (startTimeDelta TIME PATH '$.startTimeDelta')) jsontable
    

    https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=491f0f978d200a8a8522e3200509460e


    Do you also have a working idea for MySQL< 8? – Lars

    What is max amount of objects in the array on the 2nd level? – Akina

    Well it's usually less than 10 – Lars

    SELECT JSON_EXTRACT(val, CONCAT('$[0][', num, '].entries[0].startTimeDelta')) startTimeDelta
    FROM test
    -- up to 4 - increase if needed
    CROSS JOIN (SELECT 0 num UNION SELECT 1 UNION SELECT 2 UNION SELECT 3) nums
    WHERE JSON_EXTRACT(val, CONCAT('$[0][', num, '].entries[0]')) IS NOT NULL;
    

    https://www.db-fiddle.com/f/xnCCSTGQXevcpfPH1GAbUo/0