简体   繁体   中英

How do I search nested json query in mysql?

I am using MySQL 5.7+ with the native JSON data type.

Sample data:

set @jsn_string='{\"body\": {\"items\": \"[{\\\"count\\\":530,\\\"id\\\":5},{\\\"count\\\":1,\\\"id\\\":519},{\\\"count\\\":209,\\\"id\\\":522},{\\\"count\\\":0,\\\"id\\\":3004}] \"}}';

Questions: the correct answer is 530

The following query has the position of the data

select json_extract(@jsn_string,'$.body.items[0].id[0]');

but the result is: null

we can use json_unquote to remove those double quotes in items[0]

set @jsn_string='{\"body\": {\"items\": \"[{\\\"count\\\":530,\\\"id\\\":5},{\\\"count\\\":1,\\\"id\\\":519},{\\\"count\\\":209,\\\"id\\\":522},{\\\"count\\\":0,\\\"id\\\":3004}] \"}}';


select json_extract(json_unquote(json_unquote(json_extract(@jsn_string, '$.body.items[0]')))
    ,'$[0].count');

see dbfiddle

As per your sample JSON, id is not an array. So id[0] wont work As I understand from your question, you want to retrieve 530. For this you can use the following.

select json_extract(@jsn_string,'$.body.items[0].count');

Please let me know if I understood it incorrectly.

Edit - 1: I think your json is invalid. Array should not be wrapped in braces. Try this

@jsn_string='{\"body\": {\"items\": [{\\\"count\\\":530,\\\"id\\\":5},{\\\"count\\\":1,\\\"id\\\":519},{\\\"count\\\":209,\\\"id\\\":522},{\\\"count\\\":0,\\\"id\\\":3004}]}}';

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