简体   繁体   中英

Query JSON array using MySQL

I'm trying to get the data within the Rule column. It has a value in JSON format. I'm trying to construct the query to get the part which says "value":8 .

Column name: Rule .

JSON within column:

{"element":[{"maxDiscount":0,"minAmount":100,"total":{"type":"ABSOLUTE_OFF","value":8}}]}

I'm stuck with this query:

select id, rule->>'$."total"' from table A
order by id desc;

My desired output is...

ID | Value
1A | 8

You may try using the JSON path $.element[0].total.value here:

SELECT
    id,
    JSON_EXTRACT(rule, '$.element[0].total.value') AS val
FROM tableA
ORDER BY id DESC;

Is this what you are looking for?

rule ->> "$.element[0].total.value" 

This gives you the value attribute for the total entity that is the first element in the element array.

This can also be expressed:

json_extract(rule, "$.element[0].total.value") 

Demo on DB Fiddle :

select rule ->> "$.element[0].total.value" res
from (
    select cast('{"element":[{"maxDiscount":0,"minAmount":100,"total":{"type":"ABSOLUTE_OFF","value":8}}]}' as json) rule
) t
| res |
| :-- |
| 8   |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM