I want to update an existing JSON value inside a JSON array. I can append a new JSON to the JSON array using JSON_MODIFY
. Suppose i have a JSON like :
[{"id":"101","name":"John"}, {"id":"102","name":"peter"}]
But i want to update only the json with id=102.
Is it possible using JSON_MODIFY()
?
EDIT:
Actual data
{"Details":{"SId":{"Type":"string","Value":"1234"},"BookList":{"Type":"List","Value":[{"id": "101", "name": "Book1"},{"id": "102", "name": "Book2"}]},"SName":{"Type":"string","Value":"john"}}}
You can use the UPDATE statement to modify values of a JSON column in the SET clause. You can only update the JSON column, not individual portions of the JSON instance. Also, when referencing a JSON column in its entirety, the input format is the same as the INSERT statement. MERGE.
First you would need to convert it to a JavaScript Object. Once it is an Object, then you can just use dot notation into the object to change the values that you want. Lastly, you would convert that JavaScript Object back into a JSON string.
In MySQL, the JSON_SET() function inserts or updates values in a JSON document and returns the result. You provide the JSON document as the first argument, followed by the path to insert into, followed by the value to insert. You can provide multiple path/value pairs if you need to update multiple values.
Updating JSON Data (Postgresql)
If the column in your table contains json data and you want to update this data, you can use the following structure:
UPDATE table_name SET column_name = '{"key" : value}'::jsonb
WHERE column_name::jsonb @> '{“new_key” : new_value}'::jsonb;
Note: Usually @> is used as the "contains" operator.
You could use CTE
to parse it and combine path in UPDATE
part:
WITH cte AS (
SELECT *
FROM t
CROSS APPLY OPENJSON(c) s
WHERE i = 1
AND JSON_VALUE(s.value, '$.id')=102
)
UPDATE cte
SET c = JSON_MODIFY(c, '$[' + cte.[key] + '].name', 'Joe');
DBFiddle Demo
Output:
-- Before
[{"id":"101","name":"John"}, {"id":"102","name":"peter"}]
-- After
[{"id":"101","name":"John"}, {"id":"102","name":"Joe"}]
This will work on SQL Server 2017+ or SQL Azure DB otherwise you will get error. More info about path literal
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