0

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.

6
  • 1
    MySQL version???? Commented Mar 4, 2020 at 12:26
  • the version is MySQL 5 Commented Mar 4, 2020 at 12:39
  • 1
    You're out of options I am afraid. A brute force approach that uses $[x].name as path where x comes from a table of numbers 0...999 might work. Commented Mar 4, 2020 at 12:42
  • 1
    Priovide a fiddle with some sample data (or CREATE TABLE + INSERT INTO scripts). Commented Mar 4, 2020 at 13:19
  • 1
    the version is MySQL 5 Treate intermediate array as a string, and parse it using common string functions and generated numbers table. Commented Mar 4, 2020 at 13:21

1 Answer 1

1
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;

fiddle

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer @Akina this is far too complicated, and I'm only solving part of the problem, The final result would way too large to implement...
@KamelMili Update your MySQL to last version, and use JSON_TABLE() function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.