Getting data from json array mysql [duplicate] - mysql

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

MySQL 8.0 provides JSON_TABLE() to help with cases like this.
select field_options.* from fields cross join
json_table(fields.options,
'$[*]' columns(
text text path '$.text',
value text path '$.value'
)
) as field_options
where field_options.value = 1;
+-------+-------+
| text | value |
+-------+-------+
| Grass | 1 |
+-------+-------+
But you have to do this complex JSON_TABLE() expression every time you want to write such a query.
It would be simpler to not use JSON — instead, store data in a table with normal columns (one row per text/value pair). Then you can search for values you want in either column.
SELECT * FROM field_options WHERE value = '1';
99% of the uses of JSON in MySQL that I see on Stack Overflow would be solved easily by not using JSON.

Related

How do I extract a specific name-value pair from MySql JSON column? [duplicate]

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
MySQL 8.0 provides JSON_TABLE() to help with cases like this.
select field_options.* from fields cross join
json_table(fields.options,
'$[*]' columns(
text text path '$.text',
value text path '$.value'
)
) as field_options
where field_options.value = 1;
+-------+-------+
| text | value |
+-------+-------+
| Grass | 1 |
+-------+-------+
But you have to do this complex JSON_TABLE() expression every time you want to write such a query.
It would be simpler to not use JSON — instead, store data in a table with normal columns (one row per text/value pair). Then you can search for values you want in either column.
SELECT * FROM field_options WHERE value = '1';
99% of the uses of JSON in MySQL that I see on Stack Overflow would be solved easily by not using JSON.

Find the Array Element by Key-Value-Match and get the value of another key in same Array Element [duplicate]

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
MySQL 8.0 provides JSON_TABLE() to help with cases like this.
select field_options.* from fields cross join
json_table(fields.options,
'$[*]' columns(
text text path '$.text',
value text path '$.value'
)
) as field_options
where field_options.value = 1;
+-------+-------+
| text | value |
+-------+-------+
| Grass | 1 |
+-------+-------+
But you have to do this complex JSON_TABLE() expression every time you want to write such a query.
It would be simpler to not use JSON — instead, store data in a table with normal columns (one row per text/value pair). Then you can search for values you want in either column.
SELECT * FROM field_options WHERE value = '1';
99% of the uses of JSON in MySQL that I see on Stack Overflow would be solved easily by not using JSON.

How to query JSON for field match, and extract another value? [duplicate]

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
MySQL 8.0 provides JSON_TABLE() to help with cases like this.
select field_options.* from fields cross join
json_table(fields.options,
'$[*]' columns(
text text path '$.text',
value text path '$.value'
)
) as field_options
where field_options.value = 1;
+-------+-------+
| text | value |
+-------+-------+
| Grass | 1 |
+-------+-------+
But you have to do this complex JSON_TABLE() expression every time you want to write such a query.
It would be simpler to not use JSON — instead, store data in a table with normal columns (one row per text/value pair). Then you can search for values you want in either column.
SELECT * FROM field_options WHERE value = '1';
99% of the uses of JSON in MySQL that I see on Stack Overflow would be solved easily by not using JSON.

MySQL 8 search JSON key by value in array

I've got MySQL table with JSON field, where I store data in such a format.
{
"fields": {
"1": {
"s": "y"
},
"2": {
"s": "n"
}
}
}
I need to obtain the keys in fields, e.g. 1 or 2 given the value of s.
Example query:
create table mytable ( mycol json );
insert into mytable set mycol = '{"fields": {"1": {"s": "y"},"2": {"s": "n"}}}';
select j.* from mytable, JSON_TABLE(mycol,
'$.fields.*' COLUMNS (
json_key VARCHAR(10) PATH '$',
s VARCHAR(10) PATH '$.s'
)
) AS j where j.s = 'y';
gives:
# json_key, s
null, y
I would expect to get
# json_key, s
1, y
Is it possible to get that data somehow?
I don't need the results in row / table format. I would be happy to get the comma separated list of IDs (json_keys) meeting my criterium.
EDIT:
I was also thinking about getting the paths using JSON_SEARCH and passing that to JSON_EXTRACT, this was achieved here: Combining JSON_SEARCH and JSON_EXTRACT get me: "Invalid JSON path expression."
Unfortunately the difference is that I would need to use JSON_SEARCH in all mode, as I need all results. In such a mode JSON_SEARCH returns list of paths, where as JSON_EXTRACT accepts list of arguments.
Try FOR ORDINALITY (see 12.17.6 JSON Table Functions), this type enumerates rows in the COLUMNS clause:
SELECT
JSON_UNQUOTE(
JSON_EXTRACT(
JSON_KEYS(`mycol` ->> '$.fields'),
CONCAT('$[', `j`.`row` - 1, ']')
)
) `json_key`,
`j`.`s`
FROM
`mytable`,
JSON_TABLE(
`mycol`,
'$.fields.*' COLUMNS (
`row` FOR ORDINALITY,
`s` VARCHAR(10) PATH '$.s'
)
) `j`
WHERE
`j`.`s` = 'y';
See dbfiddle.

MySQL JSON: How to find object from key value

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
MySQL 8.0 provides JSON_TABLE() to help with cases like this.
select field_options.* from fields cross join
json_table(fields.options,
'$[*]' columns(
text text path '$.text',
value text path '$.value'
)
) as field_options
where field_options.value = 1;
+-------+-------+
| text | value |
+-------+-------+
| Grass | 1 |
+-------+-------+
But you have to do this complex JSON_TABLE() expression every time you want to write such a query.
It would be simpler to not use JSON — instead, store data in a table with normal columns (one row per text/value pair). Then you can search for values you want in either column.
SELECT * FROM field_options WHERE value = '1';
99% of the uses of JSON in MySQL that I see on Stack Overflow would be solved easily by not using JSON.