mysql 5.6 通过 sql 获取字符串 json key
2018-08-02 本文已影响0人
程序猿_小刚
CREATE FUNCTION `fn_Json_getKeyValue`(
in_JsonArray MEDIUMTEXT,# JSON数组字符串
in_Index TINYINT, # 从json 对象序号,序号从1开始
in_KeyName VARCHAR(512) # 键名
) RETURNS varchar(2048) CHARSET utf8
BEGIN
# 定义参数
DECLARE vs_Return VARCHAR(4096);
DECLARE vs_JsonArray, vs_Json, vs_KeyName VARCHAR(4096);
DECLARE vi_Pos1,vi_Pos2 SMALLINT UNSIGNED;
# 写入监控日志 暂不记录
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