JSON_MODIFY() is used to update the value for a given key and return the string.
Modification of data is an unavoidable task in the operational database. It helps cleaning the data in the system. But, change tracking will be covered in other blog post.
Usage:
JSON_MODIFY ( expression , path , newValue )
expression = A valid JSON value
path = A JSON path expression that specifies the property to update.
<path Expression>
[append] [ lax | strict ] $.<json path>
newValue = The new value must be a [n]varchar or text.
In lax mode, JSON_MODIFY deletes the specified key if the new value is NULL.
This function returns the updated value of expression as properly formatted JSON text.
Example :
declare @weather as nvarchar(500)
set @weather = N'{
“main”: {
“temp”: 282.55,
“feels_like”: 281.86,
“temp_min”: 280.37,
“temp_max”: 284.26,
“pressure”: 1023,
“humidity”: 100
}
}’
print ‘Is valid JSON : ‘ + str( ISJSON(@weather) )
SET @weather=JSON_MODIFY(@weather,’$.main.temp’, 300.23)
print ‘Modified value’
print @weather
output:
Is valid JSON : 1
Modified value
{
“main”: {
“temp”: 300.23,
“feels_like”: 281.86,
“temp_min”: 280.37,
“temp_max”: 284.26,
“pressure”: 1023,
“humidity”: 100
}
}