I search mysql JSON document there doesn't seem to have an easy function that can replace nested JSON object structure.
We can try to use dynamic SQL with JSON_EXTRACT
and json_keys
function.
First, we need to find updating fields of key and updated fields and use json_table
with json_keys
to get all field*
which is your updated root node.
- current:updated value.
- initial:updating value.
the result will look like
'$.dataset.field1.current', JSON_EXTRACT(col, '$.dataset.field1.initial'),
'$.dataset.field2.current', JSON_EXTRACT(col, '$.dataset.field2.initial'),
'$.dataset.field3.current', JSON_EXTRACT(col, '$.dataset.field3.initial')
Then we can try to use JSON_REPLACE
from the connect string variable.
Replaces existing values in a JSON document and returns the result.
so that final script might be like.
SET @updateFields= '';
SELECT @updateFields := group_concat(DISTINCT '''$.dataset.',fieldKey,'.current'', JSON_EXTRACT(col, ''$.dataset.',fieldKey,'.initial'')')
FROM T,
json_table(
json_keys(col,'$.dataset'),
'$[*]' COLUMNS(fieldKey VARCHAR(50) PATH '$')
) t;
set @sql := CONCAT('UPDATE T SET col = JSON_REPLACE(col,',@updateFields,')');
PREPARE dynamic_statement FROM @sql;
EXECUTE dynamic_statement;
DEALLOCATE PREPARE dynamic_statement;
sqlfiddle