3

I have a json_array [1, 2, 3, 3, 3], and I want to find out where how many the element '3' is.

For example,

json_search('[1, 2, 3, 3, 3]', 'all', 3) return null;
json_search('["1", "2", "3", "3", "3"]', 'all', '3') return ["$[2]", "$[3]", "$[4]"];

Therefore,

json_length(json_search('[1, 2, 3, 3, 3]', 'all', 3)) return null;

I want to 3

I’ve been looking all day, but I don’t know the solution and ask for help.

1

1 Answer 1

1

One option here, assuming you have just a single top level array of JSON integers, would be to use a regex replacement trick to count the number of 3's:

WITH yourTable AS (
    SELECT '[1, 2, 3, 3, 3]' AS array
)

SELECT
    LENGTH(array) - LENGTH(REGEXP_REPLACE(array, '\\b3\\b', '')) AS num_3
FROM yourTable;

This returns 3 as the length, which is correct.

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

2 Comments

I use mysql version 5.7, so I couldn't use the method you told, but I got a big idea and solved the problem. Thank you very much.
@serverwizard Thanks for the vote, but if your answer is very different than what I posted, but it worked, you should consider answering your own question (yes--you can actually do this).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.