3

I have predictions stored in a JSON field in a mysql table as follow

SELECT id, value from predictions

id | value                 |
+--------------------------+
1  | {"class1": 0.99, "class2": 0.05}
2  | {"class1": 0.94, "class2": 0.01, "class3": 0.4}
...

Each row contains a dictionary with (potentially) different keys, but each dictionnary follows this schema.

I'd like to deserialize this into a key-value result like below:

id | class  | confidence |
+------------------------+
1  | class1 | 0.99       |
1  | class2 | 0.05       |
2  | class1 | 0.94       |
2  | class2 | 0.01       |
2  | class3 | 0.4        |

Were the JSON in the format of a list containing one dictionary for each predicted class, I could have used the JSON_TABLE as I am using MySQL > 8.0, however I am at a loss on how to do so.

1 Answer 1

2

As you are using MySql 8.0 you can use JSON_KEYS(), JSON_EXTRACT() and JSON_TABLE for your requirement like below:

SELECT 
    id,
    class, 
    json_extract(value_,concat('$.',class)) confidence 
from test t1
cross join 
    json_table(
        json_keys(value_)
        , '$[*]' columns(class varchar(10) path '$')
    ) t2

DEMO

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

3 Comments

Great, thank you ! For future readers, note that if your class name contains spaces, the json path created in the JSON_EXTRACT needs to be encapsulated in double quotes as follow CONCAT('$."', class, '"')
Another question out of curiosity: is the cast of the json_keys as json necessary ? I tested without it on my use case and it works fine
It is not mandatory. Actually JSON_KEYS() return is sufficient.

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.