2

I have JSON arrays stored as strings in a MariaDB table. I want to return the rows when certain key-values are present anywhere in the array.

I performed the following test....

set @json='[{"name":"Albert","state":"IL"},{"name":"John","state":"CA"}]'

Executed the following query ...

select json_value(@json,'$[0].name')='Albert'

It got me the desired result which is...

1

Even the following query also gave me the same result(may be '*' is treated as the first element)...

select json_value(@json,'$[*].name')='Albert'

But when I provide the second name("John") in the condition, I do not get any result...

select json_value(@json,'$[*].name')='John'

Result...

0

So my observation is that when we provide the array index the "json_value" function is able to return the desired result.

Is there a way where I can avoid specifying the array index and search the desired key-value?

1

1 Answer 1

5

As commented by @dbfiddle I tried using JSON_SEARCH function.

Here is what I tried to get the desired result.

create table label_test(labels VARCHAR(1000));

insert into label_test values ('[{"name":"Albert","state":"IL"},{"name":"John","state":"CA"}]');

select * from label_test where JSON_SEARCH(labels,'all','John') like '"$[%].name"';

The result is the whole row as expected.

[{"name":"Albert","state":"IL"},{"name":"John","state":"CA"}]
Sign up to request clarification or add additional context in comments.

Comments

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.