5

How do you remove an object from a VARCHAR(MAX) JSON array?

Setup

DECLARE @Json VARCHAR(MAX) =
JSON_QUERY('[{"u":"user1","i":"item1"},{"u":"user2","i":"item2"}]')

SELECT @Json

DECLARE @NewJson VARCHAR(MAX) =
JSON_QUERY('{"u":"user3","i":"item3"}')

SELECT @NewJson

Result

[{"u":"user1","i":"item1"},{"u":"user2","i":"item2"}]

{"u":"user3","i":"item3"}

Append @NewJson to @Json

SELECT JSON_MODIFY(@Json, 'append $', JSON_QUERY(@NewJson))

Result

[{"u":"user1","i":"item1"},{"u":"user2","i":"item2"},{"u":"user3","i":"item3"}]

All good.

Remove Index 0 from @Json

SELECT JSON_MODIFY(@Json, '$[0]', NULL)

Result

[null,{"u":"user2","i":"item2"}]

I don't want index 0 to be null. I want it removed.

I can't find anything in the docs that state how to remove an object from an array.

1 Answer 1

1

I haven't worked with json but, since its a string you could do this;

SET @Json = JSON_MODIFY(@Json, '$[0]', NULL);
SET @Json = STUFF(@Json, CHARINDEX ('null,', 5, '');

Note That I can't test this code at the moment.

Sign up to request clarification or add additional context in comments.

1 Comment

Pretty hacky, but I guess it works if TSQL doesn't provide a native function for this.

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.