Skip to content

Instantly share code, notes, and snippets.

@tonidy
Forked from DaveKin/json_uniq.sql
Created February 10, 2022 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonidy/260cdbe14aa278cb6103aeb350a38dc2 to your computer and use it in GitHub Desktop.
Save tonidy/260cdbe14aa278cb6103aeb350a38dc2 to your computer and use it in GitHub Desktop.
SQL function to remove duplicate entries from a JSON array. Based on MYSQL 5.7+
CREATE FUNCTION JSON_UNIQ(arr JSON) RETURNS json
BEGIN
SET @arr = arr;
SET @a_length = JSON_LENGTH(@arr);
SET @loop_index = @a_length;
WHILE @loop_index >= 0 DO
SET @item = JSON_UNQUOTE(JSON_EXTRACT(@arr, concat('$[',@loop_index,']')));
SET @itemcount = coalesce(JSON_LENGTH(JSON_SEARCH(@arr, 'all', @item)), 0);
IF @itemcount > 1 THEN
SET @arr = JSON_REMOVE(@arr, CONCAT('$[',@loop_index,']'));
SET @loop_index = @loop_index - 1;
END IF;
SET @loop_index = @loop_index - 1;
End WHILE;
RETURN CAST(@arr AS JSON);
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment