mysql5.7支持json极大的方便了我们,但是其中json数组解析一直很麻烦,之前都是先取json数组的长度,然后遍历逐个解析,后来看了一篇博客受到启发,写了这个方法能一次全部解析出来,希望对大家有所启发。
新建jsonarray_test表并添加测试数据。
CREATE TABLE jsonarray_test (
id int(11) NOT NULL AUTO_INCREMENT,
title varchar(10) NOT NULL COMMENT '名称',
info json DEFAULT NULL COMMENT 'json数组',
UNIQUE KEY (title),
KEY id (id)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
REPLACE INTO jsonarray_test(title, info) value ('上证19','[{"Symbol": "600030", "ShortName": "中信证券"}, {"Symbol": "601166", "ShortName": "兴业银行"}, {"Symbol": "600887", "ShortName": "伊利股份"},
{"Symbol": "600000", "ShortName": "浦发银行"}, {"Symbol": "601857", "ShortName": "中国石油"}, {"Symbol": "600999", "ShortName": "招商证券"}, {"Symbol": "601006", "ShortName": "大秦铁路"},
{"Symbol": "601989", "ShortName": "中国重工"}, {"Symbol": "600104", "ShortName": "上海汽车"}, {"Symbol": "601377", "ShortName": "兴业证券"}, {"Symbol": "601390", "ShortName": "中国中铁"},
{"Symbol": "600050", "ShortName": "中国联通"}, {"Symbol": "600048", "ShortName": "保利地产"}, {"Symbol": "600111", "ShortName": "包钢稀土"}, {"Symbol": "601169", "ShortName": "北京银行"},
{"Symbol": "601800", "ShortName": "中国交建"}, {"Symbol": "600547", "ShortName": "山东黄金"}, {"Symbol": "601668", "ShortName": "中国建筑"}, {"Symbol": "601688", "ShortName": "华泰证券"}]');
REPLACE INTO jsonarray_test(title, info) value ('西藏板块','[{"Symbol": "000752", "ShortName": "西藏发展"}, {"Symbol": "000762", "ShortName": "西藏矿业"}, {"Symbol": "600211", "ShortName": "西藏药业"},
{"Symbol": "600326", "ShortName": "西藏天路"}, {"Symbol": "600338", "ShortName": "西藏珠峰"}, {"Symbol": "600749", "ShortName": "西藏旅游"}, {"Symbol": "600773", "ShortName": "西藏城投"}]');
DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_jsonarray_extract`$$
CREATE PROCEDURE `sp_jsonarray_extract`()
BEGIN
declare v_i int default 1;
DROP TABLE IF EXISTS info_incre_table;
create table info_incre_table (ID int NOT NULL,PRIMARY KEY (ID))ENGINE=MyISAM DEFAULT CHARSET=utf8; -- 自增临时表
WHILE (v_i<100) DO -- 100代表解json数组的最大长度
insert into info_incre_table values (v_i);
SET v_i=v_i+1;
END WHILE;
select a.title,substring_index(substring_index(replace(replace(replace(replace(JSON_EXTRACT(a.info,'$[*].Symbol'),' ',''),'"',''),'[',''),']',''),',',b.ID),',',-1) as symbol from jsonarray_test a
join info_incre_table b on b.ID <= (length(JSON_EXTRACT(a.info,'$[*].Symbol')) - length(replace(JSON_EXTRACT(a.info,'$[*].Symbol'),',',''))+1) order by a.title;
END$$
DELIMITER ;