简体   繁体   English

使用 MYSQL 在嵌套的 JSON 对象中提取数组

[英]Extract array in nested JSON object with MYSQL

I'm trying to extract an array from a JSON object with MYSQL我正在尝试使用MYSQLJSON对象中提取数组

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.我还尝试将 JSON 提取中'$[0]' '$[*]'更改为'$[0]'它只显示数组的第一个元素。

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.任何帮助,将不胜感激。

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.生成的数字数量必须不小于单独数组中元素的最大数量 - 如果不是,某些值将丢失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM