I'm trying to find a way to search a JSON object and get a particular key but search on another key.
Here is an example schema:
CREATE TABLE `fields` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`label` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`options` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `fields` (label, options) VALUES
(
'My Field',
'[{"text": "Grass", "value": "1"}, {"text": "Synthetic (New Type - Soft)", "value": "2"}, {"text": "Synthetic (Old Type - Hard)", "value": "3"}, {"text": "Gravel", "value": "5"}, {"text": "Clay", "value": "6"}, {"text": "Sand", "value": "7"}, {"text": "Grass/Synthetic Mix", "value": "8"}]'
);
DB Fiddle: https://www.db-fiddle.com/f/npPgVqh7fJL2JweGJ5LWXE/1
So what I would like is to select the string "Grass" from options
by giving the ID 1
.
But there doesn't seem to be a method to do that. I can get Grass by doing this:
select JSON_EXTRACT(`options`, '$[0].text') from `fields`;
// "Grass"
But that requires knowing the index from the array
I can partially get the index of the array like this:
select JSON_SEARCH(`options`, 'one', '1') from `fields`;
// "$[0].value"
And get the index itself through something really horrible like this:
select
REPLACE(REPLACE(JSON_SEARCH(`options`, 'one', '1'), '"$[', ''), '].value"', '')
from `fields`;
// 0
And even achieve what I want through something really horrible like this:
select
JSON_EXTRACT(`options`,CONCAT('$[',REPLACE(REPLACE(JSON_SEARCH(`options`, 'one', '1'), '"$[', ''), '].value"', ''), '].text'))
from `fields`;
// "Grass"
But there's got to be a better way right?
DB Fiddle: https://www.db-fiddle.com/f/npPgVqh7fJL2JweGJ5LWXE/1