How to get values from MySQL(5.6) column if that contains json document as string

前端 未结 10 703
萌比男神i
萌比男神i 2020-12-02 18:48

How to get values from MySQL(5.6) column if that contains JSON document as a string

For example, if we have a table - employee in that we have three columns id, nam

10条回答
  •  鱼传尺愫
    2020-12-02 19:35

    Offering this alternative view of the answers given here for those of you (like me) who may not intuitively see the string manipulation within the SQL functions. This version will allow you to explicitly see each step of the text parsing. This works for MySQL 5.6 and can of course be combined back together and not use any variables.

    DELIMITER $$ 
    DROP FUNCTION IF EXISTS `json_extract_c`$$
    CREATE FUNCTION `json_extract_c`(
      details TEXT,
      required_field VARCHAR (255)
    ) RETURNS TEXT CHARSET latin1
    BEGIN
      /* get key from function passed required field value */
      set @JSON_key = SUBSTRING_INDEX(required_field,'$.', -1); 
      /* get everything to the right of the 'key = ' */
      set @JSON_entry = SUBSTRING_INDEX(details,CONCAT('"', @JSON_key, '"'), -1 ); 
      /* get everything to the left of the trailing comma */
      set @JSON_entry_no_trailing_comma = SUBSTRING_INDEX(@JSON_entry, ",", 1); 
      /* get everything to the right of the leading colon after trimming trailing and leading whitespace */
      set @JSON_entry_no_leading_colon = TRIM(LEADING ':' FROM TRIM(@JSON_entry_no_trailing_comma)); 
      /* trim off the leading and trailing double quotes after trimming trailing and leading whitespace*/
      set @JSON_extracted_entry = TRIM(BOTH '"' FROM TRIM(@JSON_entry_no_leading_colon));
      RETURN @JSON_extracted_entry;
    END$$
    DELIMITER ; 
    

提交回复
热议问题