If I have a MySQL table with a JSON column called numbers
and a record that has [1, 2, 3]
in that column (array of integers), how do I update that record to remove the 2
(so it becomes [1, 3]
)?
To remove JSON element, use the delete keyword in JavaScript.
In MySQL, the JSON_UNQUOTE() function “unquotes” a JSON document and returns the result as a utf8mb4 string. You provide the JSON document as an argument, and the function will do the rest.
I was searching for an answer my self and came to this question, not wanting to use objects I continued the search. But I found a solution, you need to use a combination of json_remove
and json_search
The following removes the value 1 from the table tbl
and the column numbers
UPDATE tbl
SET numbers = JSON_REMOVE(
numbers, replace(json_search(numbers, 'one', 1), '"', '')
)
WHERE json_search(numbers, 'one', 1) IS NOT NULL
json_search
returns the path of where the value is, ie. "$[0]"
replace
remove the "
otherwise an error will occur with json_remove
json_remove
will remove the path from the json_search
resultEt voila, your value is removed.
Note: this assumes no duplicate values
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With