Reputation: 1434
I'm trying to extract an array from a JSON
object with MYSQL
SELECT json_extract(jsonObjectValue,'$[*].name') as array FROM `TEST` WHERE name='jsonObject'
The query above has this as a result
...
["elem1", "elem1", "elem2"]
["elem5", "elem1", "elem2", "elem4"]
...
I tried doing to extract the array by doing this:
SELECT json_extract(json_extract(jsonObjectValue,'$[*].name'),'$[*]') as array FROM `TEST` WHERE name='jsonObject'
The desired result would look like this:
...
"elem1"
"elem1"
"elem2"
"elem5"
"elem1"
"elem2"
"elem4"
...
but the actual result is:
...
["elem1", "elem1", "elem2"]
["elem5", "elem1", "elem2", "elem4"]
...
I also tried to change '$[*]'
inside the JSON extract to '$[0]'
it only shows the first element of the array.
Update
to reproduce the issue run these queries:
CREATE TABLE `TEST` (
`jsonObjectValue` varchar(1000) NOT NULL,
`name` varchar(1000) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
and for the data run:
INSERT INTO `TEST` (`jsonObjectValue`, `name`) VALUES
('[{\"name\":\"elem1\"},{\"name\":\"elem1\"},{\"name\":\"elem2\"}]',
'JsonObject'),
('test', 'name'),
('test2', 'test2'),
('[{\"name\":\"elem5\"},{\"name\":\"elem1\"},{\"name\":\"elem2\"},
{\"name\":\"elem4\"}]', 'jsonObject');
Any help would be appreciated.
Upvotes: 0
Views: 631
Reputation: 42844
SELECT TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(arrays.array, ',', numbers.num), ',', -1)) element
FROM ( SELECT TRIM('[' FROM TRIM(']' FROM json_extract(jsonObjectValue,'$[*].name'))) as array
FROM `TEST`
WHERE name='jsonObject') arrays,
( SELECT 1 num UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 ) numbers
WHERE numbers.num <= LENGTH(arrays.array) - LENGTH(REPLACE(arrays.array, ',', '')) + 1;
PS. The amount of numbers generated must be not less than the max amount of elements in separate array - if not some values will be lost.
Upvotes: 1