Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

MySQL atualiza objetos JSON específicos em uma matriz


Uma opção:
DROP PROCEDURE IF EXISTS `sp_update_json`;

DELIMITER //

CREATE PROCEDURE `sp_update_json`(
  `json` JSON,
  `value` VARCHAR(255)
)
BEGIN
  DECLARE `array_objects` JSON DEFAULT
    REPLACE(JSON_SEARCH(`json`,
                'all',
                'loud',
                NULL,
                '$.parrot[*].volume'
               ), 'volume', 'says');
  DECLARE `max_objects` INT UNSIGNED DEFAULT 
    JSON_LENGTH(`array_objects`);
  DECLARE `current_object` INT UNSIGNED DEFAULT 0;
  WHILE `current_object` < `max_objects` DO
    SET `json` := JSON_REPLACE(`json`, 
                           JSON_UNQUOTE(                             
                             JSON_EXTRACT(
                               `array_objects`,
                               CONCAT('$[', `current_object`, ']')
                             )
                           ), `value`);
    SET `current_object` := `current_object` + 1;
  END WHILE;
  SELECT `json`;
END//

DELIMITER ;

SET @`j` := '
{
  "cat": "meow", 
  "dog": "woof", 
  "parrot": [
    {"volume": "quiet", "says": "hello"}, 
    {"volume": "loud", "says": "polly"},
    {"volume": "loud", "says": "cracker"}
  ]
}';

CALL `sp_update_json`(@`j`, 'pretty bird');

Consulte db-fiddle .