0

I have in mysql json field with the values:

{"a": true, "b":true, "c":false, "d":true}

I want to retrieve in SQL, for each row, only the keys and values that are true.

For example in the row:

{"a": true, "b":true, "c":false, "d":true}

the result will be:

{"a": true, "b":true, "d":true}

How can I do it?

Thank you!

1 Answer 1

3

Using string (regex) functions:

SELECT id,
       val, 
       REGEXP_REPLACE(REGEXP_REPLACE(val, '(, *)?"[^"]+": *false', ''), '\\{ *, *', '\\{') without_false
FROM test

Using recursive CTE:

WITH RECURSIVE
cte AS ( SELECT id, val src, val FROM test
         UNION ALL
         SELECT id, 
                src,
                JSON_REMOVE(val, JSON_UNQUOTE(JSON_SEARCH(REPLACE(val, 'false', '"false"'), 'one', 'false')))
         FROM cte
         WHERE JSON_SEARCH(REPLACE(val, 'false', '"false"'), 'one', 'false') IS NOT NULL
         )
SELECT id, src val, val without_false
FROM cte
WHERE JSON_SEARCH(REPLACE(val, 'false', '"false"'), 'one', 'false') IS NULL

fiddle

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.