mysql5.7以下 json字段处理

时间:2023-01-28 20:14:48
CREATE DEFINER=`your_dbname`@`%` FUNCTION `fn_Json_getKeyValue`(`in_JsonArray` VARCHAR(4096),`in_Index` tinyint,`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;  
  
#获取json字段 key值  
  
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