Extract data from object out of json array in mySQL

56 views Asked by At

I have a mySQL database with a table named “orders”. In this table I have a column named ids which is JSON.

The JSON looks like

[
    {
         "type" : "master",
         "id" : "100"
    },
    {
         "type" : "slave",
         "id" : "101"
    },
    {
         "type" : "slave",
         "id" : "102"
    },
    ....
]

There is always only one entry a master. I need a select, which gives me the id of the object which is of type master.

How can I do this?

1

There are 1 answers

4
Salman A On BEST ANSWER

You can use MySQL JSON_TABLE function to convert the JSON into rows/columns, then apply a WHERE clause:

SELECT *
FROM orders, json_table(
    orders.ids,
    '$[*]'
    COLUMNS(
        type VARCHAR(100) PATH '$.type',
        id VARCHAR(100) PATH '$.id'
    )
) AS jt
WHERE jt.type = 'master'