Reputation: 410
How can I find path to object with property "is_true": true
?
JSON in data column:
[
{
"myData": {},
"is_true": true
},
{
"myData": {},
"is_true": false
},
{
"myData": {},
"is_true": false
}
]
Failed attempts:
SELECT JSON_SEARCH(data, "all", true) AS booleanObject FROM my_table
and...
SELECT JSON_SEARCH(data, "all", "true") AS booleanObject
SELECT JSON_SEARCH(data, "all", "%true%") AS booleanObject
SELECT JSON_SEARCH(data, "all", true) AS booleanObject
SELECT JSON_SEARCH(data, "all", 1) AS booleanObject
SELECT JSON_SEARCH(data, "all", true, NULL, "$") AS booleanObject
etc.
Upvotes: 4
Views: 1840
Reputation: 16551
This is an unintuitive option and you should be careful with performance issues:
SELECT
JSON_SEARCH(
REPLACE(
REPLACE(
REPLACE(
JSON_EXTRACT(@`json`, '$[*].is_true'),
', ',
'", "'
),
'[',
'["'
),
']',
'"]'
), 'all', 'true') `positions`;
See dbfiddle.
Upvotes: 1
Reputation: 272136
Unfortunately it looks like JSON_SEARCH
only searches string values. You could use brute force:
SELECT x.i, JSON_EXTRACT(data, CONCAT('$[', x.i, ']')) AS obj
FROM t
INNER JOIN (
SELECT 0 AS i UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3
) AS x ON x.i < JSON_LENGTH(t.data)
WHERE JSON_EXTRACT(data, CONCAT('$[', x.i, '].is_true')) = true
If you're using MySQL 8 then a more elegant option is to use JSON_TABLE
:
SELECT x.i, x.obj
FROM t
CROSS JOIN JSON_TABLE(t.data, '$[*]' COLUMNS(
i FOR ORDINALITY,
is_true BOOLEAN PATH '$.is_true',
obj JSON PATH '$'
)) AS x
WHERE x.is_true = true
Upvotes: 2
Reputation: 116
SELECT JSON_EXTRACT(is_true, "$[0].is_true") AS is_true
FROM table
WHERE JSON_EXTRACT(is_true, "$[0].is_true") = 1
Upvotes: 0