Extract data from json inside mysql field

前端 未结 5 1376
无人共我
无人共我 2021-01-04 20:47

I\'ve got a a table with rows, and one of the rows has a field with data like this

{\"name\":\"Richard\",\"lastname\":null,\"city\":\"Olavarria\",\"cityId\":         


        
5条回答
  •  青春惊慌失措
    2021-01-04 21:09

    I have wrapped this into a stored function for those constrained to MySQL <5.7.7:

    CREATE FUNCTION `json_extract_string`(
        p_json text,
        p_key text
    ) RETURNS varchar(40) CHARSET latin1
    BEGIN
        SET @pattern = CONCAT('"', p_key, '":"');
        SET @start_i = LOCATE(@pattern, p_json) + CHAR_LENGTH(@pattern);
        if @start_i = CHAR_LENGTH(@pattern) then
            SET @end_i = 0;
        else
            SET @end_i = LOCATE('"', p_json, @start_i) - @start_i;
        end if;
        RETURN SUBSTR(p_json, @start_i, @end_i);
    END
    

    Note this only works with string values but is a bit more robust than @DmitryK's answer, in that it returns an empty string if the key is not found and the key can be anywhere in the JSON string.

提交回复
热议问题