1. 程式人生 > >mysql5.7以下自定義函式解析json

mysql5.7以下自定義函式解析json

DELIMITER $$


USE `dw`$$


DROP FUNCTION IF EXISTS `fn_Json_getKeyValue`$$


CREATE DEFINER=`data`@`%` FUNCTION `fn_Json_getKeyValue`(
in_JsonArray VARCHAR(4096),#JSON陣列字串
in_Index TINYINT, #JSON物件序號,序號從1開始
in_KeyName VARCHAR(64)#鍵名
) RETURNS VARCHAR(512) CHARSET utf8
BEGIN
DECLARE vs_return VARCHAR(4096);
DECLARE vs_JsonArray, vs_Json, vs_KeyName VARCHAR(4096);
#declare vs_Json varchar(4096);
DECLARE vi_pos1, vi_pos2 SMALLINT UNSIGNED;

#寫監控日誌
#insert into dw.t_etl_log(sp_name, title, description) 
#values('dw.fn_Json_getKeyValue', '通過Json鍵名取鍵值', concat('in_JsonArray=', in_JsonArray));

SET vs_JsonArray = TRIM(in_JsonArray);
SET vs_KeyName = TRIM(in_KeyName);

IF vs_JsonArray = '' OR vs_JsonArray IS NULL 
OR vs_KeyName = '' OR vs_KeyName IS NULL 
OR in_Index <= 0 OR in_Index IS NULL THEN
SET vs_return = NULL;
ELSE
#去掉方括號
SET vs_JsonArray = REPLACE(REPLACE(vs_JsonArray, '[', ''), ']', '');
#取指定的JSON物件
SET vs_json = SUBSTRING_INDEX(SUBSTRING_INDEX(vs_JsonArray,'}', in_index),'}',-1);

IF vs_json = '' OR vs_json IS NULL THEN
SET vs_return = NULL;
ELSE
SET vs_KeyName = CONCAT('"', vs_KeyName, '":');
SET vi_pos1 = INSTR(vs_json, vs_KeyName);
IF vi_pos1 > 0 THEN
#如果鍵名存在
SET vi_pos1 = vi_pos1 + CHAR_LENGTH(vs_KeyName);
SET vi_pos2 = LOCATE(',', vs_json, vi_pos1);
IF vi_pos2 = 0 THEN
#最後一個元素沒有','分隔符,也沒有結束符'}'
SET vi_pos2 = CHAR_LENGTH(vs_json) + 1;
END IF;
SET vs_return = REPLACE(MID(vs_json, vi_pos1, vi_pos2 - vi_pos1), '"', '');
END IF;
END IF;
END IF;


RETURN(vs_return);
END$$


DELIMITER ;


測試: {"old_current_score":"2","new_current_score":"0","old_grade_id":"1","new_grade_id":"1","grade_time":"2016-04-09 00:43:26","grade_upgrade_time":"2017-04-09 00:43:26"}
 select fn_Json_getKeyValue(reason,1,'old_grade_id');