4

I want to delete the "AttributeName" : "Manufacturer" from the below json in SQL Server 2016:

declare @json nvarchar(max) = '[{"Type":"G","GroupBy":[],
"Attributes":[{"AttributeName":"Class Designation / Compressive Strength"},{"AttributeName":"Size"},{"AttributeName":"Manufacturer"}]}]'

This is the query I tried which is not working

select JSON_MODIFY((
select JSON_Query(@json, '$[0].Attributes') as res),'$.AttributeName.Manufacturer', null) 

1 Answer 1

3

Here is the working solution using the for json and open json. The point is to:

  1. Identify the item you wish to delete and replace it with NULL. This is done by JSON_MODIFY(@json,'$[0].Attributes[2]', null). We're simply saying, take the 2nd element in Attributes and replace it by null

  2. Convert this array to a row set. We need to somehow get rid of this null element and that's something we can filter easily in SQL by where [value] is not null

  3. Assemble it all back to original JSON. That's done by FOR JSON AUTO

Please bear in mind one important aspect of such JSON data transformations:

JSON is designed for information exchange or eventually to store the information. But you should avoid more complicated data manipulation on SQL level.

Anyway, solution here:

declare @json nvarchar(max) = '[{"Type": "G","GroupBy": [],"Attributes": [{"AttributeName": "Class Designation / Compressive Strength"}, {"AttributeName": "Size"}, {"AttributeName": "Manufacturer"}]}]';            

with src as
(
    SELECT * FROM OPENJSON(
        JSON_Query(
            JSON_MODIFY(@json,'$[0].Attributes[2]', null) , '$[0].Attributes'))
)
select JSON_MODIFY(@json,'$[0].Attributes', (
    select JSON_VALUE([value], '$.AttributeName') as [AttributeName] from src
    where [value] is not null
    FOR JSON AUTO 
)) 
Sign up to request clarification or add additional context in comments.

2 Comments

That's pretty cool. works as expected. One small clarification , In real scenario I know only the AttributeName = Manufacturer to be deleted but not its Index as 2 "JSON_MODIFY(@json,'$[0].Attributes[2]', null)".
@Jebin You see :) Yet another reason to move the transformation logic somewhere else. It will get increasingly more and more painful. Anyway, the only way out here is to replace the [2] index by subselect.. a query that will find the element index by its attributename value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.