Removing a JSON property

To remove a property from the input JSON string, you have to use a JSON path expression in lax mode. You will repeat the preceding code, but this time in lax mode:

DECLARE @json NVARCHAR(MAX) = N'{ 
"Album":"Wish You Were Here", 
"Year":1975, 
"Members":["Gilmour","Waters","Wright","Mason"] 
}'; 
PRINT JSON_MODIFY(@json, '$.Year', NULL); 

When you observe the result of this action, you can see that the Year property does not exist anymore:

{
"Album":"Wish You Were Here",
"Members":["Gilmour","Waters","Wright","Mason"]
}

By taking this approach, you can remove only properties and their values. You cannot remove an array element. The following code will not remove the Waters element from the JSON array property Members; it will actually update it to NULL:

DECLARE @json NVARCHAR(MAX) = N'{ 
"Album":"Wish You Were Here", 
"Year":1975, 
"Members":["Gilmour","Waters","Wright","Mason"] 
}'; 
PRINT JSON_MODIFY(@json, '$.Members[1]', NULL); 

The result is as follows:

{
"Album":"Wish You Were Here",
"Year":1975,
"Members":["Gilmour",null,"Wright","Mason"]
}

If you want to remove the Waters element, you can use the following code:

DECLARE @json NVARCHAR(MAX) = N'{ 
"Album":"Wish You Were Here", 
"Year":1975, 
"Members":["Gilmour","Waters","Wright","Mason"] 
}'; 
PRINT JSON_MODIFY(@json, '$.Members', JSON_QUERY('["Gilmour","Wright","Mason"]')); 

And finally, the expected result:

{
"Album":"Wish You Were Here",
"Year":1975,
"Members":["Gilmour","Wright","Mason"]
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.214.60